我是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,
},
],
})
但是我仍然遇到相同的错误。有人能指出我正确的方向吗?
谢谢
答案 0 :(得分:0)
您应该注入商店,而不是直接注入州模型。
因此,用protected store: fromClientAuth.State
代替protected store: Store<fromClientAuth.State>
应该至少可以解决第一个问题。
@Injectable()
export class ApiService {
constructor(
protected httpClient: HttpClient,
protected store: Store<fromClientAuth.State>,
) {
}
PS:您可以在函数的最后一个参数的末尾留下逗号。