【发布时间】: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