Reputation: 635
Current situation:
i have a service.ts which save data in the backend:
public update(route: string, values: Array<any>): Observable<boolean> {
let body = { values: values };
return this.httpClient.put(route, body, {
observe: 'response'
})
.map((res) => {
let status = res.status;
switch (status) {
case 202:
return true;
}
}, error => {
switch (error.status) {
case 406:
return false;
}
});
}
i have a http interceptor so i can append token to every request:
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(request)
.do(event => {
})
.catch((error: any) => {
});
}
and i have a component with a save method, where i normaly need the result:
public save(form: FormGroup) {
let path = '...';
this.service.update(path, form.value)
.subscribe(result => {
// success
}, error => {
// fail
});
}
I dont know how to put things together. I trigger the save method in my component and also need the result (success, error) in the component.
Right now i can only grab the result in my interceptor. But this is the wrong place for it.
Upvotes: 0
Views: 63
Reputation: 5088
public update(route: string, values: Array<any>): Observable<boolean> {
let body = { values: values };
return this.httpClient.put(route, body, {
observe: 'response'
});
}
// You don't need map for httpClient
Then the correct way to implement HttpInterceptor
is:
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do(
(response: HttpEvent<any>) => {
// Do stuff with success 'response instanceof HttpResponse'
},
(error: any) => {
// Do stuff with error 'error instance of HttpErrorResponse'
});
}
Upvotes: 1