app.component.ts
import { Component } from "@angular/core";
import { AppService } from "./service/app.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
constructor(private service : AppService){
this.service.appStore.subscribe(state => {
console.log(state);
})
}
ngOnInit(){
this.service.getData();
}
testClick(){
console.log("111")
}
}
app.service.ts
import { Data } from "../mock/data";
import { Person } from "../models/person";
import { Observable } from "rxjs/Observable";
import { Store } from "@ngrx/store";
import { AppState, createAppState } from "../app.state";
import { AppAction } from "../actions/app.action";
import { Injectable } from "@angular/core";
@Injectable()
export class AppService{
appStore: Store<AppState>;
constructor(private store : Store<any>){
this.appStore = this.store.select(createAppState);
}
getData() {
this.store.dispatch(new AppAction({
data : Data
}));
}
}
app.state.ts
import { createFeatureSelector, createSelector } from "@ngrx/store";
import { Person } from "./models/person";
export class AppState {
entity : Array<Person> = [];
}
export const getAppState = createFeatureSelector<AppState>("app");
export const createAppState = createSelector(
getAppState,
(state: AppState) => new AppState()
)
app.reducer.ts
import { AppState } from "../app.state";
import { AppAction } from "../actions/app.action";
export function appReducer(
state = new AppState(),
action : AppAction
) {
switch(action.type){
case "appAction" : {
let s = new AppState();
console.log(action.payload.data)
s.entity = action.payload.data;
return s;
}
default: {
return new AppState();
}
}
}
app.action.ts
import { Action } from "@ngrx/store";
import { Person } from "../models/person";
export class AppAction implements Action{
type = "appAction";
constructor(
public payload :{
data : Array<Person>
}
){
}
}
Why can"t you subscribe to the value sent by action. Entity is an empty array, and the switch of reducer can clearly print out the value.