在使用@ngrx/store 时,这是在class 中访问状态变量的正确方法吗?

Is this the correct way to access state variables within a class when using @ngrx/store?

我有一项服务需要根据存储在 AppState 中的变量值做出决策。这是我的服务的极大简化版本:

import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';

interface AppState {
  foo: boolean;
}

@Injectable()
export class FooProvider {

  private isFoo: boolean;

  constructor(private store: Store<AppState>) {
    // is it foo?
    store.pipe(select('foo')).subscribe((foo: boolean) => {
      this.isFoo = foo;
    });
  }

  isItFoo = (): string => this.isFoo ? "it's foo!" : 'nope, not foo';
}

Question: Is this the "right" way to access and use a variable stored in the AppState within a class in an app using @ngrx/store?

Component 中,我相信我可以通过 async 管道更简单地使用 foo 变量,如下所示:

import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';

interface AppState {
  foo: boolean;
}

@Component(
  selector: 'foo-component',
  template: `<p>{{ ( foo$ | async ) ? "it's foo!" : "nope, not foo" }}</p>`
)
export class FooComponent {

  private foo$: Observable<boolean>;

  constructor(private store: Store<AppState>) {
    this.foo$ = store.pipe(select('foo'));
  }
}

是否有 better/easier/more 访问 class 中的状态变量的正确方法?

this issue 中所述,在 ngrx 中有意删除了获取当前值的功能,因为它被滥用了,现在只能通过 hack 实现:

function getValue(o) {
  let value;
  o.take(1).subcribe(v => {
    value = v;
  });
  return value;
}

可观察对象的目的是提供数据流。存储值可以更改,如果使用它的服务没有重新实例化,它将继续使用旧值。因此,预计一旦有一个流,它就会被转换并与其他流结合,并仅在它被消费的地方订阅(大多数时候这将是一个视图,它可以与 async 管道一起使用)。

在这种情况下它将是:

isItFoo$ = store.pipe(
  select('foo'),
  map((foo: boolean) => foo ? "it's foo!" : 'nope, not foo')
);