怎么在Angular5中实现状态管理-创新互联

这篇文章给大家介绍怎么在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: `
 
   
    特价展示
    列表展示
  
    
 `,  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: `
  
   详情页{{id}}    返回   
 `, }) 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中实现状态管理就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


新闻名称:怎么在Angular5中实现状态管理-创新互联
本文URL:http://scyanting.com/article/csidoh.html

其他资讯