Angular5中状况治理

前面进修了vue,react 都有状况治理,如vue中的vuex是全局状况治理,在任何组件里都能够援用状况治理中的数据,一样,react中的redux和mbox也是,但碰到angular5却不知道了。
一年前运用过angular1.x做过项目,当时全局状况能够运用$rootscope,也能够运用效劳Service完成,下面就用Service体式格局在angular5中完成下吧
先定义状况治理对象,须要存什么数据,本身定义

export class UserInfo {
  public userInfo: boolean;
  constructor(){
      this.userInfo = true;  //设置全局的掌握导航是不是显现
  }
}

然后定义Service,以下

import { Injectable} from '@angular/core';
import { Headers, Http } from '@angular/http';
import { UserInfo } from './user-info.model';

@Injectable()  //注入效劳
export class ListsService{
  private  userInfo;
  constructor(private http: Http) { 
    this.userInfo = new UserInfo();
  }

  //设置路由显现的状况
  setUserInfo(v) {
    this.userInfo.userInfo = v;
  }
  //猎取路由显现的状况
  getUserInfo() {
    return this.userInfo;
  }
}

设置了service肯定要在ngmodule中导入,如许才在此module中有用

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';   
import { HttpModule }    from '@angular/http';

import { AppComponent } from './app.component'; 

import { AppRouterModule } from './router.module'; 
import { ViewComponent } from './view.component';
import { ListComponent } from './list.component';
import { OtherComponent } from './other.component';
import { DetailComponent } from './detail.component'; 
import { ListsService } from './app.service';

@NgModule({
  declarations: [
    AppComponent,
    DetailComponent,
    ViewComponent,
    ListComponent,
    OtherComponent
  ],
  imports: [  
    BrowserModule,
    FormsModule ,
    AppRouterModule,
    HttpModule
  ],
  providers: [ListsService], 
  bootstrap: [AppComponent]  
})
export class AppModule { }  

然后就能够在component中运用了

@Component({
  selector: 'app-root',
  template: `
  <div >
      <div class="lists" *ngIf='userInfo.userInfo'>
        <a routerLink="/view" routerLinkActive ="active">特价展现</a>
        <a routerLink="/list" routerLinkActive ="active">列表展现</a>
    </div>
    <router-outlet></router-outlet>
  </div>
  `,
  styles:[`
  .lists a{
    padding:0 10px;
  }
  .active{
    color: #f60;
  }
  `]
})
export class AppComponent {
  private  userInfo;
 constructor(private listsService: ListsService) { 
      this.userInfo= this.listsService.getUserInfo();
 }
}

在详情页中经由过程转变状况来转变页面

@Component({
  selector: 'app-detail',
  template: `
    <div>
      详情页{{id}}
      <button (click)="goBack()">返回</button>
    </div>

  `,
})
export class DetailComponent {
  private  userInfo;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private listsService: ListsService
  ) {
    this.userInfo= this.listsService.setUserInfo(false);
  }
  goBack(): void {
    this.location.back();
  }
  //组件烧毁时实行
  ngOnDestroy():void{
    this.userInfo= this.listsService.setUserInfo(true);
  }
}

好了,如许就ok了。
如有疑问,请加群交换:654979292

    原文作者:weistar103
    原文地址: https://segmentfault.com/a/1190000016235417
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞