Reputation: 83
I have a login.component
login() {
this.accountService.login(this.model)
.subscribe(
response => {
//do stuff
},
(error: AppError) => {
// do stuff
},
);
a login service
login(loginModel: LoginModel) {
return this.http.post('auth/login/', loginModel).pipe(
tap(response => {
if (response) {
//add jwt to local storage
}
}));
}
and a httpinterceptor
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerSettings: { [ name: string ]: string | string[]; } = {};
return this.localStorage.getItem(AppStorageKeys.JWT).pipe(
mergeMap((token: any) => {
if (token)
//add to headers etc
const apiReq = req.clone({ url: `${environment.apiBase}/${req.url}`, headers: newHeader });
return next.handle(apiReq);
}));
}
When login fails the login.component shows the error. When login is successful, the token is retrieved from the api successfully, as I can see from the network tab in dev tools, but the value is never stored in the map function in login.service nor is the response => {} function called within the login.component.ts - yet error does?
What am I doing wrong?
----- Edit:
I've created a stackblitz but it is working on there, which is leading me to believe it might be because my login.component and service are in a child module, to the interceptor.
Upvotes: 0
Views: 213
Reputation: 14199
As noted in the comments, Angular 6 HttpClient
will only accept JSON as a response per default. In order to change the acceptable response type, add a third parameter to the post
function call, like so:
return this.http.post('auth/login/', loginModel, {responseType: 'text'})
More info on that can be found here: https://angular.io/guide/http#requesting-non-json-data
Upvotes: 1