重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

怎么在Angular5中实现状态管理

这篇文章给大家介绍怎么在Angular5中实现状态管理,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

十年的新宾网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网整合营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整新宾建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联从事“新宾网站设计”,“新宾网站推广”以来,每个客户项目都认真落实执行。

先定义状态管理对象,需要存什么数据,自己定义

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中实现状态管理
网站网址:http://cqcxhl.cn/article/gdishi.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP