您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在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); } }
關于怎么在Angular5中實現狀態管理就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。