Issue
I'm am just wondering which one is the best practice for angular.
Here is an observable method.
downloadRequest(ids: number[], url: string, inputName: string): Observable<void> {
const formData = new FormData();
formData.append(inputName, ids.join(','));
return this.http.post<void>(url, formData)
}
This is the subscribe method that I use.
this.downloadService.downloadRequest(data.blabla, url, 'blabla').subscribe(res => {
alert('HEY');
}, err => {
console.log(err);
});
In this case, this alert is going to work only if the response status equals 200. Is it right? The observable method returns void. So, I can not get a response status for sure.
Instead, should I use the below case? The observable method returns any. I can get a response status.
downloadRequest(ids: number[], url: string, inputName: string): Observable<any> {
const formData = new FormData();
formData.append(inputName, ids.join(','));
return this.http.post<any>(url, formData, {observe: 'response'})
}
this.downloadService.downloadRequest(data.blabla, url, 'blabla').subscribe(res => {
if (res.status === 200) {
alert('HEY');
}
}, err => {
console.log(err);
});
Solution
When you subscribe to an Observable returned by HttpClient
, you can specify up to 3 callbacks, in order:
next
, which receives the body of the successful response (or null if the successful response had no body)error
, which receives the error the prevented this request from succeedingcomplete
, which is invoked afternext
if the request was successful
As you can see, next
is invoked for every successful request, even if the response has no body.
So, I can not get a response status for sure.
That is a misunderstanding. Every HTTP response contains a response code. It may or may not contain a body, but it will always contain a response code, and that indicates whether the request was successful, and determines whether HttpClient will invoke next
or error
.
As an aside, all response codes of the form 2xx indicate success, not just 200. Receiving a 201 Created
or a 204 No Content
is no cause for alarm.
Answered By - meriton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.