image.png

    1. import { Injectable } from '@angular/core';
    2. @Injectable({
    3. providedIn: 'root'
    4. })
    5. export class CommonService {
    6. public defaultCity:string = "武汉"
    7. constructor() { }
    8. getCity(){
    9. if(localStorage.getItem("city")){
    10. this.defaultCity =localStorage.getItem("city")
    11. }
    12. return this.defaultCity;
    13. }
    14. changeCity(value:string){
    15. this.defaultCity = value;
    16. localStorage.setItem("city",value)
    17. }
    18. }
    1. import { Component, OnInit } from '@angular/core';
    2. import {CommonService} from '../../services/common.service'
    3. @Component({
    4. selector: 'app-home',
    5. templateUrl: './home.component.html',
    6. styleUrls: ['./home.component.css']
    7. })
    8. export class HomeComponent implements OnInit {
    9. public hotCities:string [] =["北京","上海","深圳","武汉","杭州"]
    10. public city:any
    11. constructor(public common:CommonService) { }
    12. ngOnInit() {
    13. this.city = this.common.getCity()
    14. }
    15. handlecilck(city:string){
    16. console.log(city)
    17. this.common.changeCity(city)
    18. }
    19. }

    使用

    1. <p>{{common.defaultCity}}</p>
    2. <h2>热门城市</h2>
    3. <button *ngFor="let item of hotCities" class="bin"
    4. (click)="handlecilck(item)">{{item}}</button>