Home > Software design >  What is the best practice for subscribe method in angular?
What is the best practice for subscribe method in angular?

Time:11-23

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);
 });

CodePudding user response:

With normal case of http.post method.

It only return the content of body or exception and it's enough, we often only want to get content of request. That's why it's used as default behavior.

Sometimes, we need to access other fields like status, https then second way must be used.

You can customize the data return HttpResponse.

From document:

https://angular.io/guide/http#reading-the-full-response

https://angular.io/api/common/http/HttpResponse

CodePudding user response:

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 succeeding
  • complete, which is invoked after next 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.

  • Related