gpt4 book ai didi

angular - 使用@ngrx/store 时,这是访问类内状态变量的正确方法吗?

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:08 24 4
gpt4 key购买 nike

我有一项服务需要根据存储在 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'));
}
}

有没有更好/更容易/更正确的方法来访问类中的状态变量?

最佳答案

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

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

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

在这种情况下,它将是:

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

关于angular - 使用@ngrx/store 时,这是访问类内状态变量的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49146053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com