在AngularX中使用ngrx 【附源碼】

来源:http://www.cnblogs.com/besuccess/archive/2017/07/09/7140834.html
-Advertisement-
Play Games

ngrx 是 Angular框架的狀態容器,提供可預測化的狀態管理。 1.首先創建一個可路由訪問的模塊 這裡命名為:DemopetModule。 包括文件:demopet.html、demopet.scss、demopet.component.ts、demopet.routes.ts、demopet ...


ngrx 是 Angular框架的狀態容器,提供可預測化的狀態管理。

1.首先創建一個可路由訪問的模塊 這裡命名為:DemopetModule。

   包括文件:demopet.html、demopet.scss、demopet.component.ts、demopet.routes.ts、demopet.module.ts

    代碼如下:

 demopet.html

<!--暫時放一個標簽-->
<h1>Demo</h1>

 demopet.scss

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 {


}

整體代碼結構如下:

運行效果如下:只是為了學習方便,能夠有個運行的模塊

 

2.安裝ngrx

npm install @ngrx/core --save

npm install @ngrx/store --save

npm install @ngrx/effects --save

@ngrx/store是一個旨在提高寫性能的控制狀態的容器

 

3.使用ngrx

首先瞭解下單向數據流形式

代碼如下:

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
        };
    }
}

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;
        }
    }
}

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

        case PettagActions.LOAD_INFO_SUCCESS:{

            return action.payload;
        }

        default:{

            return state;
        }
    }
}

 NOTE:Action中定義了我們期望狀態如何發生改變   Reducer實現了狀態具體如何改變

Action與Store之間添加ngrx/Effect   實現action非同步請求與store處理結果間的解耦

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));
}

 

 

4.修改demopet.module.ts 添加 ngrx支持

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.調用ngrx實現數據列表獲取與單個詳細信息獲取

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<PetTag>,
    private action: PettagActions
  ) {

    this.dataArr = store.select('pet');
  }

  ngOnInit() {

    this.store.dispatch(this.action.loadData());
  }

  ngOnDestroy() {

    this.sub.unsubscribe();
  }

  info() {

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

}

demopet.html

<h1>Demo</h1>



<pre>
   <ul>
        <li *ngFor="let d of dataArr | async"> 
            DEMO :  {{ d.msg }}
            <button (click)="info()">info</button>
        </li>
    </ul>

    {{ dataItem | async | json }}

    <h1 *ngFor="let d of dataItem | async"> {{ d.msg }} </h1>
</pre>

 

6.運行效果

初始化時候獲取數據列表

 

 點擊info按鈕  獲取詳細詳細

 

7.以上代碼是從項目中取出的部分代碼,其中涉及到HttpService需要自己封裝,data.json demo.json兩個測試用的json文件,名字隨便取的當時。

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);
    }



}

 

8.模塊源代碼  下載

 

9.我的微信公眾號。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一 概述 1.什麼是重載? 利用形參區分同一個類中多個同名方法的機制叫做重載。 2.什麼是重寫? 子類繼承父類,重寫父類方法的過程叫做重寫。 二 對比 1.發生範圍 重寫發生在父類與子類之間,涉及兩個類,重載發生在同一個類內部。 2.約束 重寫 重載 重載正是根據方法的形參來區分同名的方法,所以同名 ...
  • Java中的集合框架(中) 由於Java中的集合框架的內容比較多,在這裡分為三個部分介紹Java的集合框架,內容是從淺到深,如果已經有java基礎的小伙伴可以直接跳到<淺入深出之Java集合框架(下)>。 目 錄 淺入深出之Java集合框架(上) 淺入深出之Java集合框架(中) 淺入深出之Java ...
  • Descriptions: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate ...
  • 環境: python2.7 ComsenzXP自帶MySQL 安裝python-MySQL模塊 數據格式:txt格式的賬號信息。 數據一行一條數據。 難點:有的行只有賬號,沒有密碼;有的為空行;有的行首行尾有三連引號;有的空行;有的不是賬號密碼信息。 代碼實現: ...
  • 一、java中的序列化 當兩個進程在進行遠程通信時,彼此可以發送各種類型的數據。無論是何種類型的數據,都會以二進位序列的形式傳送。發送方需要把這個Java對象轉換為位元組序列,才能在網路上傳送;接收方則需要把位元組序列再恢復為Java對象。把Java對象轉換為位元組序列的過程稱為對象的序列化。把位元組序列恢 ...
  • 一、管道流 演示:PipedInputStream , PipedOutputStream 註意:管道流本身就不建議在一個線程中使用,這是因為向輸出流中寫的數據,都會存到輸入流內部的一個1024位元組大小的數組中,如果寫的內容超過這個數組的大小,而且沒有被輸入流讀取的話,輸出流所在的線程就會等待,如果 ...
  • MyBatis介面的簡單實現原理 用過MyBatis3的人可能會覺得為什麼MyBatis的Mapper介面沒有實現類,但是可以直接用? 那是因為MyBatis使用Java動態代理實現的介面。 這裡僅僅舉個簡單例子來說明原理,不是完全針對MyBatis的,這種思想我們也可以應用在其他地方。 定義一個接 ...
  • 我在工作的時候,在測試環境下使用的資料庫跟生產環境的資料庫不一致,當我們的測試環境下的資料庫完成測試準備更新到生產環境上的資料庫時候,需要準備更新腳本,真是一不小心沒記下來就會忘了改了哪裡,哪裡添加了什麼,這個真是非常讓人頭疼。因此我就試著用Python來實現自動的生成更新腳本,以免我這爛記性,記不 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...