鍍金池/ 問答/HTML5  HTML/ Angular為什么subscribe訂閱不到值?

Angular為什么subscribe訂閱不到值?

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

為什么訂閱不了action發(fā)過來的值。entity居然是空數(shù)組,reducer的switch明明可以打印出值。
圖片描述

回答
編輯回答
久愛她

app.state.ts 中的 createAppState 一直在返回一個(gè)新的new出來的對(duì)象。

2017年3月4日 09:29