一、service
1-1 生成服务
ng g service services/common
1-2 在根模块中配置
//app.module.tsimport {CommonService} from './services/common.service';@NgModule({providers: [CommonService]})export class AppModule { }
1-3 组件使用服务
export class CommonService {public defaultCity:string = "武汉"constructor() { }}//1.导入服务import {CommonService} from '../../services/common.service'export class HomeComponent implements OnInit {//2.构造函数中配置constructor(public common:CommonService) { }ngOnInit() {//3.使用console.log(this.common.defaultCity);}}
1-4 更改服务
//组件中
<button *ngFor="let item of hotCities" (click)="handleClick(item)">{{item}}</button>handleClick(item:string){console.log(item)this.common.changeCity(item);}
//servicechangeCity(value:string){this.defaultCity=value;}
1-5 缓存
//servicegetCity(){if(localStorage.getItem("city")){this.defaultCity=localStorage.getItem("city")}return this.defaultCity}changeCity(value:string){...localStorage.setItem("city",value)}
//组件export class HomeComponent implements OnInit {public city:any;constructor(public common:CommonService) { }ngOnInit() {this.city=this.common.getCity()}}
二、生命周期和DOM获取
ngAfterViewInit(){//推荐在此生命周期函数中操作DOM}
2-1 ViewChild
//1.给DOM命名<div #app *ngIf="flag">显示</div>//2.配置ViewChildimport { Component, OnInit,ViewChild } from '@angular/core';export class AboutComponent implements OnInit {@ViewChild('app',{static:false}) app:any;ngAfterViewInit(){console.log(this.app);}}
