Reputation: 12015
I use interceptor in last Angular:
return next.handle(request).pipe(
map((event: any) => {
if (request.method == "GET") {
return event;
}
if (request.method == "POST") {
if (event.body) {
return event.body["result"];
}
}
return event;
}));
So, I check if it is POST
request, I expect to get data from JSON with key result
.
Also I tried to return data in Observer:
if (event.body) {
return Observable.of(event.body["result"]);
}
And subscription is:
this.method.subscribe(res => {
console.log(res);
});
Look at this pic:
console.log(event); // This is default event - first selected area
console.log(eventToSend); /./ This is modified - second selected area
Difference is type HttpResponse, it lacks in second modified object eventToSend
Upvotes: 2
Views: 1005
Reputation: 12015
I solved this issue using this approach:
return next.handle(request).pipe(
map((event: any) => {
if (request.method == "POST") {
if (request.body["$type"] == "LoginRequest") {
return event;
}
if (event.body) {
event.body = event.body["result"];
}
}
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.route.navigate(["/login"]);
}
return throwError(
"Ошибка сервера RequestInterception: " + error.message || error
);
})
);
Upvotes: 1
Reputation: 39432
Since your interceptor needs to return the complete event
(of type Observable<HttpEvent<any>>
) instead of just the response body
, but you still want to get just result
in the response body
, try this:
return next.handle(request).pipe(
map((event: any) => {
// Removing this as it is redundant
/*if (request.method == "GET") {
return event;
}*/
if (request.method == "POST") {
if (event.body) {
const eventToSend = { ...event };
eventToSend.body = event.body["result"];
return eventToSend;
}
}
return event;
}));
Here, we're spreading the whole event
object, and then reassigning the body
property on it with body['result']
Here's a Sample StackBlitz for your ref.
Upvotes: 1