Answer the question
In order to leave comments, you need to log in
Angular HttpInterceptor: why can't I get a response?
There is an interceptor class:
import {
HttpRequest,
HttpEvent,
HttpHandler,
HttpInterceptor,
HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { messages } from 'src/fake-backend/data/messages/messages';
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('HTTP REQUEST INTERCEPTED BY THE MOCKED BACKEND');
const duplicate = req.clone({ body: {data: messages} });
return next.handle(duplicate);
}
}
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: FakeBackendInterceptor, multi: true }
],
@Injectable({
providedIn: 'root'
})
export class MessageService {
constructor(
private http: HttpClient
) { }
getMessages(): Observable<Message[]> {
return this.http.get('/messages')
.map((messages: Message[]) => {
console.log('MessageService : getMessages : ', messages);
return messages;
});
}
}
this.messageService.getMessages()
.subscribe(messages => {
console.log('ChatComponent : getMessages : ', messages);
});
Answer the question
In order to leave comments, you need to log in
Response and request are mixed up in the interceptor code.
What is happening now:
1. The interceptor intercepts the request object
2. The interceptor adds { body: {data: messages} }
to the request 3. The interceptor passes the request further to the reverse
I understand that the idea of the interceptor is to catch the request and instead of passing the request further back, return the answer.
Try something like this:
import {
HttpRequest,
HttpEvent,
HttpHandler,
HttpInterceptor,
HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { messages } from 'src/fake-backend/data/messages/messages';
import { of } from 'rxjs/observable/of';
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('HTTP REQUEST INTERCEPTED BY THE MOCKED BACKEND');
return of(new HttpResponse({body: {data: messages}}));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question