一、service

1-1 生成服务

  1. ng g service services/common

1-2 在根模块中配置

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

1-3 组件使用服务

  1. export class CommonService {
  2. public defaultCity:string = "武汉"
  3. constructor() { }
  4. }
  5. //1.导入服务
  6. import {CommonService} from '../../services/common.service'
  7. export class HomeComponent implements OnInit {
  8. //2.构造函数中配置
  9. constructor(public common:CommonService) { }
  10. ngOnInit() {
  11. //3.使用
  12. console.log(this.common.defaultCity);
  13. }
  14. }

1-4 更改服务

//组件中

  1. <button *ngFor="let item of hotCities" (click)="handleClick(item)">{{item}}</button>
  2. handleClick(item:string){
  3. console.log(item)
  4. this.common.changeCity(item);
  5. }
  1. //service
  2. changeCity(value:string){
  3. this.defaultCity=value;
  4. }

1-5 缓存

  1. //service
  2. getCity(){
  3. if(localStorage.getItem("city")){
  4. this.defaultCity=localStorage.getItem("city")
  5. }
  6. return this.defaultCity
  7. }
  8. changeCity(value:string){
  9. ...
  10. localStorage.setItem("city",value)
  11. }
  1. //组件
  2. export class HomeComponent implements OnInit {
  3. public city:any;
  4. constructor(public common:CommonService) { }
  5. ngOnInit() {
  6. this.city=this.common.getCity()
  7. }
  8. }

二、生命周期和DOM获取

  1. ngAfterViewInit(){
  2. //推荐在此生命周期函数中操作DOM
  3. }

2-1 ViewChild

  1. //1.给DOM命名
  2. <div #app *ngIf="flag">
  3. 显示
  4. </div>
  5. //2.配置ViewChild
  6. import { Component, OnInit,ViewChild } from '@angular/core';
  7. export class AboutComponent implements OnInit {
  8. @ViewChild('app',{static:false}) app:any;
  9. ngAfterViewInit(){
  10. console.log(this.app);
  11. }
  12. }