NGRX is a state container for the Angular framework that provides predictable state management.

1. Create a routable module named DemopetModule.

The following files are available: demopet. HTML, demopet. SCSS, demopet.component.ts, demopet.routes

The code is as follows:Copy the code

Demopet. HTML

Demo

h1{ color:#d70029; } demopet.component.ts

import { Component} from ‘@angular/core’;

@Component({ selector: ‘demo-pet’, styleUrls: [‘./demopet.scss’], templateUrl: ‘./demopet.html’ }) export class DemoPetComponent { //nothing now… } demopet.routes.ts

import { DemoPetComponent } from ‘./demopet.component’;

export const routes = [ { path: ”, pathMatch: ‘full’, children: [ { path: ”, component: DemoPetComponent } ] } ]; demopet.module.ts

import { CommonModule } from ‘@angular/common’; import { FormsModule } from ‘@angular/forms’; import { NgModule } from ‘@angular/core’; import { RouterModule } from ‘@angular/router’; import { routes } from ‘./demopet.routes’;

@NgModule({ declarations: [ DemoPetComponent, ], imports: [ CommonModule, FormsModule, RouterModule.forChild(routes) ], providers: [ ] }) export class DemoPetModule {

} The overall code structure is as follows:

The running effect is as follows: just for learning convenience, can have a running module

2. Install NGRX

npm install @ngrx/core –save

npm install @ngrx/store –save

npm install @ngrx/effects –save

@ngrx/ Store is a container of control state designed to improve write performance

3. Use NGRX

First understand the form of one-way data flow

The code is as follows:

pet-tag.actions.ts

import { Injectable } from ‘@angular/core’; import { Action } from ‘@ngrx/store’;

@Injectable() export class PettagActions{ static LOAD_DATA=’Load Data’; loadData():Action{ return { type:PettagActions.LOAD_DATA }; }

static LOAD_DATA_SUCCESS='Load Data Success';
loadDtaSuccess(data):Action{
    return {
        type:PettagActions.LOAD_DATA_SUCCESS,
        payload:data
    };
}


static LOAD_INFO='Load Info';
loadInfo():Action{
    return {
        type:PettagActions.LOAD_INFO
    };
}

static LOAD_INFO_SUCCESS='Load Info Success';
loadInfoSuccess(data):Action{
    return {
        type:PettagActions.LOAD_INFO_SUCCESS,
        payload:data
    };
}
Copy the code

} pet-tag.reducer.ts

import { Action } from ‘@ngrx/store’; import { Observable } from ‘rxjs/Observable’; import { PettagActions } from ‘.. /action/pet-tag.actions’;

export function petTagReducer(state:any,action:Action){ switch(action.type){

case PettagActions.LOAD_DATA_SUCCESS:{ return action.payload; } // case PettagActions.LOAD_INFO_SUCCESS:{ // return action.payload; // } default:{ return state; }}Copy the code

}

export function infoReducer(state:any,action:Action){ switch(action.type){

case PettagActions.LOAD_INFO_SUCCESS:{ return action.payload; } default:{ return state; }}Copy the code

} NOTE: The actions define how we expect the state to change

NGRX /Effect is added between Action and Store to decouple asynchronous Action requests from Store processing results

pet-tag.effect.ts

import { Injectable } from ‘@angular/core’; import { Effect,Actions } from ‘@ngrx/effects’; import { PettagActions } from ‘.. /action/pet-tag.actions’; import { PettagService } from ‘.. /service/pet-tag.service’;

@Injectable() export class PettagEffect {

constructor(
    private action$:Actions,
    private pettagAction:PettagActions,
    private service:PettagService
){}


@Effect() loadData=this.action$
            .ofType(PettagActions.LOAD_DATA)
            .switchMap(()=>this.service.getData())
            .map(data=>this.pettagAction.loadDtaSuccess(data))


@Effect() loadInfo=this.action$
            .ofType(PettagActions.LOAD_INFO)
            .switchMap(()=>this.service.getInfo())
            .map(data=>this.pettagAction.loadInfoSuccess(data));
Copy the code

}

4. Modify demopet.module.ts to add NGRX support

import { StoreModule } from ‘@ngrx/store’; import { EffectsModule } from ‘@ngrx/effects’; import { PettagActions } from ‘./action/pet-tag.actions’; import { petTagReducer,infoReducer } from ‘./reducer/pet-tag.reducer’; import { PettagEffect } from ‘./effect/pet-tag.effect’; @NgModule({ declarations: [ DemoPetComponent, ], imports: [ CommonModule, FormsModule, RouterModule.forChild(routes), //here new added StoreModule.provideStore({ pet:petTagReducer, info:infoReducer }), EffectsModule.run(PettagEffect) ], providers: [ PettagActions, PettagService ] }) export class DemoPetModule { }

5. Call NGRX to obtain data list and single details

demopet.component.ts

import { Component, OnInit, ViewChild, AfterViewInit } from ‘@angular/core’; import { Observable } from “rxjs”; import { Store } from ‘@ngrx/store’; import { Subscription } from ‘rxjs/Subscription’; import { HttpService } from ‘.. /shared/services/http/http.service’; import { PetTag } from ‘./model/pet-tag.model’; import { PettagActions } from ‘./action/pet-tag.actions’;

@Component({ selector: ‘demo-pet’, styleUrls: [‘./demopet.scss’], templateUrl: ‘./demopet.html’ }) export class DemoPetComponent {

private sub: Subscription; public dataArr: any; public dataItem: any; public language: string = ‘en’; public param = {value: ‘world’};

constructor( private store: Store, private action: PettagActions ) {

this.dataArr = store.select('pet');
Copy the code

}

ngOnInit() {

this.store.dispatch(this.action.loadData());
Copy the code

}

ngOnDestroy() {

this.sub.unsubscribe();
Copy the code

}

info() {

console.log('info');
this.dataItem = this.store.select('info');
this.store.dispatch(this.action.loadInfo());
Copy the code

}

} demopet.html

Demo

   
  • DEMO : {{ d.msg }} info

{{ d.msg }}

6. Operation effect

Get the list of data at initialization time

Click the Info button for details

7. The above code is taken from the project part of the code, which involves the HttpService needs their own packaging, data.json demo. Json two test json file, name arbitrary at the time.

http.service.ts

import { Inject, Injectable } from ‘@angular/core’; import { Http, Response, Headers, RequestOptions, URLSearchParams } from ‘@angular/http’; import { Observable } from “rxjs”; import ‘rxjs/add/operator/map’; import ‘rxjs/operator/delay’; import ‘rxjs/operator/mergeMap’; import ‘rxjs/operator/switchMap’; import ‘rxjs/add/operator/catch’; import ‘rxjs/add/observable/throw’; import { handleError } from ‘./handleError’; import { rootPath } from ‘./http.config’;

@Injectable() export class HttpService {

private _root: string=""; constructor(private http: Http) { this._root=rootPath; } public get(url: string, data: Map<string, any>, root: string = this._root): Observable<any> { if (root == null) root = this._root; let params = new URLSearchParams(); if (!! data) { data.forEach(function (v, k) { params.set(k, v); }); } return this.http.get(root + url, { search: params }) .map((resp: Response) => resp.json()) .catch(handleError); }Copy the code

}

8. Wechat official account