【问题标题】:How do I inject store dependencies with ngrx如何使用 ngrx 注入存储依赖项
【发布时间】:2019-11-20 06:39:04
【问题描述】:

我是 Angular 的新手,也是 ngrx 的新手...

我有一个注射问题,我确信很容易克服,只要我理解它,但我现在正在兜圈子,一次有太多新概念。 看起来很简单。当应用程序加载时,我使用 clientId/clientSecret 使用 clientauth.service 进行身份验证并返回一个令牌。此令牌保存在存储中,并用于通过 api.service 对 API 的任何进一步请求。

app.component.ts

this.store.dispatch(new ClientAuthActions.ClientAuthLoginRequest({ clientId: environment.clientId, clientSecret: environment.clientSecret }));

clientauth.effect.ts

constructor(
    private actions$: Actions,
    protected authService: ClientAuthService,
  ) {}

@Effect()
  login$ = this.actions$.pipe(
    ofType(clientauthActions.ClientAuthActionTypes.ClientAuthLoginRequest),
    switchMap((user: ClientAuthUser) => {
      return this.authService.login(user)
      .pipe(
        map((token: ClientAuthToken) => {
          return new clientauthActions.ClientAuthLoginSuccess(token);

        }),
        catchError(error => of(new clientauthActions.ClientAuthLoginFailure({error}))) //TODO, handle the error
      )
    })
  );
}

clientauth.service.ts

@Injectable()
export class ClientAuthService {
  constructor(
    protected apiService: ApiService,
  ) {
  }

  login(user: ClientAuthUser) {
.....
   return this.apiService.postClientLogin(user);
  }

api.service.ts

@Injectable()
export class ApiService {
  constructor(
    protected httpClient: HttpClient,
    protected store: fromClientAuth.State,
    ) {
  }


  getHttpHeaders(): HttpHeaders {

    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
    });

    if (this.store.token) {
     return headers.append('Authorization', `Bearer ${this.store.token.accessToken}`);
    }

    return headers;
  }

  postClientLogin(...);

但是我的依赖注入有问题,我得到了错误:错误:无法解析 ApiService 的所有参数:([object Object],?)。

我尝试将以下内容添加到我的 app.module.ts 中,但我仍然得到相同的结果,而且我显然在这里遗漏了一些东西。

import * as fromClientAuth from './store/reducers/clientauth.reducer';

export const CLIENTAUTH_REDUCER_TOKEN = new InjectionToken<
  ActionReducerMap<fromClientAuth.State>
>('ClientAuth Reducers');

export function getReducers(): ActionReducerMap<fromClientAuth.State> {
  // map of reducers (I guess something is missing here, but I don't know how to complete it)
  return {}
}

@NgModule({
...
imports:[
...
    StoreModule.forRoot(reducers, {
      metaReducers, 
      runtimeChecks: {
        strictStateImmutability: true,
        strictActionImmutability: true,
      }
    }),
    StoreModule.forFeature(fromClientAuth.featureKey, CLIENTAUTH_REDUCER_TOKEN),
    EffectsModule.forRoot([AppEffects, ClientAuthEffects]),
],
providers: [
    ApiService,
    ClientAuthService,
    {
      provide: CLIENTAUTH_REDUCER_TOKEN,
      useFactory: getReducers,
    },
  ],
})

但我仍然遇到同样的错误。有人可以指出我正确的方向吗?

谢谢

【问题讨论】:

    标签: angular ngrx ngrx-store


    【解决方案1】:

    您应该注入 Store 而不是直接注入您的 State 模型。

    所以用protected store: Store&lt;fromClientAuth.State&gt; 替换protected store: fromClientAuth.State 至少应该解决第一个问题。

    @Injectable()
    export class ApiService {
      constructor(
        protected httpClient: HttpClient,
        protected store: Store<fromClientAuth.State>,
        ) {
      }
    

    PS:你可以在函数的最后一个参数的末尾留一个逗号。

    【讨论】:

      猜你喜欢
      • 2011-11-22
      • 2020-09-28
      • 1970-01-01
      • 2010-11-27
      • 2015-09-12
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多