1、生成服务

  1. ng g service services/common

2、根模块中配置服务模块

  1. //app.module.ts
  2. import {CommonService} from './services/common.service';
  3. @NgModule({
  4. ...,
  5. providers: [CommonService],
  6. })

3、在具体的组件中使用服务

3-1、在服务中配置

  1. //services/.ts
  2. import { Injectable } from '@angular/core';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class CommonService {
  7. public defaultCity:string = '武汉'
  8. constructor() { }
  9. }

3-2、导入服务

  1. //.ts
  2. import {CommonService} from '../../services/common.service';
  3. export class HomeComponent implements OnInit {
  4. public city:any;
  5. public hotCities:string [] = ["北京","上海","广州","深圳"];
  6. constructor(public common:CommonService) { }
  7. ngOnInit() {
  8. // console.log(this.common.defaultCity)
  9. this.city = this.common.defaultCity;
  10. }
  11. }

3-3、使用

  1. //组件
  2. //.html
  3. <p>{{city}}</p>
  4. <button *ngFor="let item of hotCities" class="btn" (click)="handleClick(item)">{{item}}</button>
  1. //.ts
  2. export class HomeComponent implements OnInit {
  3. ...
  4. handleClick(item:string){
  5. console.log(item)
  6. }
  7. }

3-4、把选中的地点返回到组件

3-4-1、在services中设置方法

  1. //.ts
  2. export class CommonService {
  3. public defaultCity:string = '武汉'
  4. constructor() { }
  5. changeCity(value:string){
  6. this.defaultCity = value;
  7. }
  8. }

3-4-2、在组件中

  1. //.ts
  2. export class HomeComponent implements OnInit {
  3. ...
  4. handleClick(item:string){
  5. console.log(item)
  6. this.common.changeCity(item);
  7. }
  8. }
  1. //.html
  2. <p>{{common.defaultCity}}</p>
  3. <h2>热门城市</h2>
  4. <button *ngFor="let item of hotCities" class="btn"
  5. (click)="handleClick(item)">{{item}}</button>

3-4-3、加缓存

  1. //services/.ts
  2. export class CommonService {
  3. ...
  4. getCity(){
  5. if(localStorage.getItem("city")){
  6. this.defaultCity = localStorage.getItem("city")
  7. }
  8. return this.defaultCity;
  9. }
  10. changeCity(value:string){
  11. this.defaultCity = value;
  12. localStorage.setItem("city",value);
  13. }
  14. }

3-4-4、数据持久化

  1. //组件
  2. //.ts
  3. export class HomeComponent implements OnInit {
  4. public hotCities:string [] = ["北京","上海","广州","深圳"];
  5. public city:any;
  6. constructor(public common:CommonService) { }
  7. ngOnInit() {
  8. this.city = this.common.getCity();
  9. }
  10. ...
  11. }

3-5、另一种方法(3-4)

  1. //services/.ts
  2. changeCity(value:string){
  3. // this.defaultCity = value; //不要这行
  4. localStorage.setItem("city",value);
  5. }
  1. //组件
  2. //.ts
  3. export class HomeComponent implements OnInit {
  4. public hotCities:string [] = ["北京","上海","广州","深圳"];
  5. public city:any;
  6. constructor(public common:CommonService) { }
  7. ngOnInit() {
  8. this.city = this.common.getCity();
  9. }
  10. handleClick(item:string){
  11. console.log(item)
  12. this.common.changeCity(item);
  13. }
  14. //添加以下函数
  15. ngDoCheck(){
  16. this.city = this.common.getCity();
  17. }
  18. }