这篇文章给大家介绍怎么在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。