ngrx / store将商店注入服务

时间:2017-08-21 20:46:11

标签: angular dependency-injection ngrx ngrx-store

我使用nularx / 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');

1 个答案:

答案 0 :(得分:1)

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

1。)您需要使用@Injectable()

为跟踪器服务添加前缀

2.。)跟踪服务上的wasInjected正在询问== null,如果它不为空,则会返回false,如果您提出问题则无效#34} ;被注射&#34;。所以我倒了那张支票。

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

相关问题