【问题标题】:ngrx/store Inject a store into a servicengrx/store 将 store 注入到服务中
【发布时间】:2018-01-30 00:14:19
【问题描述】:

我正在使用 ngrx/store v4.0.2 和 Angular 4.3.3。

我想做的是从服务中访问商店:

/********* Module *************/
import { StoreModule, Store } from '@ngrx/store';

@NgModule({
imports: [
    CommonModule,
    StoreModule.forFeature('feature1', reducers),
     //...
     ],
declarations: [ /*...*/ ],
exports: [],
providers: [
    AuthDataService
]
export class MyModule { }

/********* AuthDataService *************/
import { Store } from '@ngrx/store';
import { AuthDataState } from '../reducers/auth';

export class AuthDataService {
    constructor(private state: Store<AuthDataState>){
        this.state.select(getIsLoggedIn).subscribe(in => {
              console.log("User 'loggedIn' is now set to:" + in);
         });
    }
}

但是,我总是收到undefined,而商店对于同一模块中的组件工作得很好。

如何从服务内部访问组件可用的同一个商店?

这是笨蛋:http://plnkr.co/edit/1Lxq82

编辑 - 问题已修复
问题在于getIsLoggedIn。那是:

export const getIsLoggedIn = (state: AuthDataState) => state.IsLoggedIn;

应该是:

export const getIsLoggedIn = createFeatureSelector<AuthDataState>('feature1');

【问题讨论】:

    标签: angular dependency-injection ngrx ngrx-store


    【解决方案1】:

    我在您的 plnkr 中发现了一些错误

    1.) 您需要在跟踪器服务前加上@Injectable()

    2.) 您在跟踪器服务上的 wasInjected 询问的是 == null,如果它不为 null,它将返回 false,如果您问的是“被注入”的问题,这没有任何意义。所以我把那张支票倒过来了。

    在这里更新了 plnkr http://plnkr.co/edit/KVLpHS

    【讨论】:

    • 不,不是这样...我已经添加了 plnkr 链接,玩得开心:)
    • 更新了我的答案,在您的 plnkr 中发现了问题。另外,我分叉了你的 plnkr(上面的链接)并删除了一堆东西来查找错误。 (存储路由器的东西等等)。应该对最终答案影响不大。
    • 谢谢...这解决了 plnkr,我还发现了我的选择器的问题 - 我直接访问商店,我应该使用 createFeatureSelector(即 createSelector.. . 在我为 SO 而笨拙的原始问题中,问题出在使用StoreModule.forFeature 注册商店的子模块中)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多