I have an Ionic app that has a user
provider with a signup()
method:
doSignup() {
// set
I was using ngrx with Angular to store the token. I faced this error in my interceptor.ts
.
The wrong code was this:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this._store
.pipe(
select(fromSelectors.selectAuth),
)
.subscribe((state: fromReducers.AuthState) => {
if (state.token != null) {
const clonedReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + state.token)
});
return next.handle(clonedReq);
}
else {
this.router.navigate(['login']);
}
});
}
I fixed the code by returning the flow:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this._store
.pipe(
select(fromSelectors.selectAuth),
switchMap((state: fromReducers.AuthState) => {
if (state.token != null) {
const clonedReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + state.token)
});
return next.handle(clonedReq);
}
else {
this.router.navigate(['login']);
// return EMPTY stream
return of({}) as Observable<HttpEvent<any>>;
}
})
);
}
Resolved here the right way :)
I have been facing this issue when trying to authenticate a user using JSON Web Token. in my case it's related to authentication interceptor.
Sending a request to authenticate a user doesn't have to provide a token since it doesn't exist yet.
Check that your interceptor include this:
if (req.headers.get('No-Auth') == "True")
return next.handle(req.clone());
And that you provide {'No-Auth':'True'}
to your header's request like this:
authenticateUser(user): Observable<any> {
const headers = new HttpHeaders({'No-Auth':'True'});
headers.append('Content-Type', 'application/json');
return this.httpClient.post(`${this.apiEndpoint}/auth/authenticate`, user, {headers: headers});
}
In my case, the error was caused by a different problem.
I was providing the service in two different points. I had written:
@Injectable({provideIn: 'root'}) and I was also providing the module in the app.module.ts. So if you encountered this error you can check this before going ahead
In my case, the error was caused by a different problem.
I was providing the service in two different points. I had written:
@Injectable({provideIn: 'root'})
and I was also providing the module in the app.module.ts
. So if you encountered this error you can check this before going ahead