1、生成服务
ng g service services/common
2、根模块中配置服务模块
//app.module.tsimport {CommonService} from './services/common.service';@NgModule({ ..., providers: [CommonService],})
3、在具体的组件中使用服务
3-1、在服务中配置
//services/.tsimport { Injectable } from '@angular/core';@Injectable({ providedIn: 'root'})export class CommonService { public defaultCity:string = '武汉' constructor() { }}
3-2、导入服务
//.tsimport {CommonService} from '../../services/common.service';export class HomeComponent implements OnInit { public city:any; public hotCities:string [] = ["北京","上海","广州","深圳"]; constructor(public common:CommonService) { } ngOnInit() { // console.log(this.common.defaultCity) this.city = this.common.defaultCity; }}
3-3、使用
//组件//.html<p>{{city}}</p><button *ngFor="let item of hotCities" class="btn" (click)="handleClick(item)">{{item}}</button>
//.tsexport class HomeComponent implements OnInit { ... handleClick(item:string){ console.log(item) }}
3-4、把选中的地点返回到组件
3-4-1、在services中设置方法
//.tsexport class CommonService { public defaultCity:string = '武汉' constructor() { } changeCity(value:string){ this.defaultCity = value; }}
3-4-2、在组件中
//.tsexport class HomeComponent implements OnInit { ... handleClick(item:string){ console.log(item) this.common.changeCity(item); }}
//.html<p>{{common.defaultCity}}</p><h2>热门城市</h2><button *ngFor="let item of hotCities" class="btn" (click)="handleClick(item)">{{item}}</button>
3-4-3、加缓存
//services/.tsexport class CommonService { ... getCity(){ if(localStorage.getItem("city")){ this.defaultCity = localStorage.getItem("city") } return this.defaultCity; } changeCity(value:string){ this.defaultCity = value; localStorage.setItem("city",value); }}
3-4-4、数据持久化
//组件//.tsexport class HomeComponent implements OnInit { public hotCities:string [] = ["北京","上海","广州","深圳"]; public city:any; constructor(public common:CommonService) { } ngOnInit() { this.city = this.common.getCity(); } ...}
3-5、另一种方法(3-4)
//services/.tschangeCity(value:string){ // this.defaultCity = value; //不要这行 localStorage.setItem("city",value);}
//组件//.tsexport class HomeComponent implements OnInit { public hotCities:string [] = ["北京","上海","广州","深圳"]; public city:any; constructor(public common:CommonService) { } ngOnInit() { this.city = this.common.getCity(); } handleClick(item:string){ console.log(item) this.common.changeCity(item); } //添加以下函数 ngDoCheck(){ this.city = this.common.getCity(); }}