Angular为什么subscribe订阅不到值?

发布于 2022-09-07 07:28:40 字数 2754 浏览 19 评论 0

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发过来的值。entity居然是空数组,reducer的switch明明可以打印出值。
图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海夜未眠 2022-09-14 07:28:40

app.state.ts 中的 createAppState 一直在返回一个新的new出来的对象。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文