如何使用store.select()在Angular2中使用ngrx获取根级别状态?

时间:2017-05-12 11:35:32

标签: angular ngrx

我一直在努力解决这个问题。

我正在尝试使用Angular2中的ngrx来获取存储在redux存储中的对象的引用。我有以下情况:

import {User} from "./user";

export class SessionState{
  constructor(
    public user: User,
    public currentCompanyId: number,
    public currentDepartmentId: number
  ) { }
}

然后是以下代码:

export class SidebarComponent implements OnInit {

  constructor(private sessionStore: Store<SessionStore>, private router: Router,) { }

  sessionState: Observable<SessionState>;
  user: Observable<User>;
  currentCompanyId: Observable<number>;
  currentDepartmentId: Observable<number>;

  ngOnInit(){
    this.sessionState = this.sessionStore.select("sessionState");
    this.user = this.sessionStore.select("user");
    this.user.subscribe(user => console.log(user));
    this.sessionState.subscribe(state => console.log(state));
  }
}

现在用户打印出来就好了,但整个sessionState给出了一个未定义的。我尝试使用select(“”),select()和此方法的其他替代方法,但似乎无法找到获取整个sessionState的可观察对象的正确方法。

这里出了什么问题?

1 个答案:

答案 0 :(得分:0)

export class SidebarComponent implements OnInit {


  constructor(private sessionStore: Store<SessionStore>, private router: 
Router,) { }

  user: Observable<User>;
  currentCompanyId: Observable<number>;
  currentDepartmentId: Observable<number>;

  ngOnInit(){
    this.sessionStore.subscribe(state => console.log(state));

    this.user = this.sessionStore.select(state => state.user);
    this.user.subscribe(user => console.log(user));

  }
}