SoFunction
Updated on 2025-04-12

Detailed explanation of the request request method of angular4 that is basically encapsulated

Why encapsulate?

The request method provided by angular4 itself is implemented using Observable. It uses the observer mode, which I personally think is very convenient for writing requests.

There will be many different requests in a project, but in fact each request will have some commonalities. For example: Each request must be authorized. For example, each request must first determine that the status field returned by the background is 200 before the request is successful. The data returned by the background is in the data field, such as the processing of error information is the same... etc.

Therefore, we need to encapsulate a request to handle these problems uniformly, so as to ensure that the values ​​received when calling the request method in the component can be used directly, and there is almost no need to write some duplicate code.

What do you hope to encapsulate?

Of course, the fewer duplicate code, the better. We just want to be lazy! ! ! !

How to achieve it?

First, create a new requested service, the file name is:. Then follow me to the virtual requirements and take the step by step to improve this service.

Requirements A

1. The request method is get.

2. The default request timeout is 3 seconds, and other timeout times can be passed in.

3. The successful json returned in the background is as follows:

{
  "status": 200,
  "data"  : ...
}

When error is:

{
  "status": 201,
  "msg"  : "Error in username or password"
}

Implement A

/**
  ******************************************************************************************************************************************
  * @App: test
  * @author: isiico
  * @type: service
  * @src: services/
  *
  * @descriptions:
  * Requested Service
  *
  ******************************************************************************************************************************************
  */
// Angular Core
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

// rxjs
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/observable/throw';

@Injectable()
export class RequestService {
  private setTimeout = 3000; // Default timeout
  constructor(private http:HttpClient) {
  }
  
   /** Get data
     * param: url string required, requested url
     * time number can not be filled in. The requested timeout time. If not filled in, the default is setTimeout
     * return: Observable HttpClient get request, the value type returned after the request is any
     **/
   public getData(url, time = ):Observable<any> {
    let thiUrl = url; // The url used    let thisTime = time; // Timeout time used    return (thiUrl)
       .timeout(thisTime)
       .map(res => (res));
   }

   /** Processing of return data
     * param: data any required, data to be processed
     * return: res any Return the processed value
     **/
   private resFun(data:any):any {
    let thisData:any = data; // Values ​​to be processed    let res:any; // Final value
    // When status is 200    if (thisData['status'] == 200) {
       res = thisData['data']; // Assign the final value    } else {
    // When status is not 200      let err = thisData['msg']; // error message      throw new Error(err); // Throw an error    }
    return res; // Return the final value   }
}

Requirement B

1. For security, the background requires the authorization parameter to be added to the header of the request.

2. When the request fails (such as 404, 500), the error message is processed well. The final error message should be the string type error message that can be used directly like in implementation A.

Implement B

(Only the newly added code is displayed, the complete code is followed by)

import 'rxjs/add/operator/catch';

@Injectable()
export class RequestService {

   /** Add the Authorization property */
   private addAuthorization(options:any):void { 
    options['headers'] = { 
       'Authorization': '1drf5dg4d7s4w7z', 
    }; 
   } 
  
   /** Get data
     * param: url string required, requested url
     * time number can not be filled in. The requested timeout time. If not filled in, the default is setTimeout
     * return: Observable HttpClient get request, the value type returned after the request is any
     **/
   public getData(url, time = ):Observable<any> {
    let thiUrl = url; // The url used    let options = {}; // Requested settings    let thisTime = time; // Timeout time used    (options); // Add Authorization parameter in the request header    return (thiUrl, options)
       .timeout(thisTime)
       .catch() // Handle error information (must be placed between timeout and map)       .map(res => (res));
   }

  /** Handling of request error information
     * param: err any Required, error information to be processed
     * return: res string Processed result
     **/
   public httpErrorFun(err:any):string { /* new */
    let res:string = ''; // Processed result /* new */    let data:any = err; // Values ​​to be processed /* new */
    /** When an error message is returned in the background */
    if (('error') && ('message')) { /* new */
       res = ; /* new */

     /** When the background does not return an error message only has an error name */
    } else if (('name')) { /* new */
       let errName = ; /* new */

     /** Request timeout */
     if (errName == 'TimeoutError') { /* new */
      res = 'Sorry, the request timed out'; /* new */
     }

     /** Backend return when unauthorized */
    } else if (data == "Unauthorization") { /* new */
       res = 'You do not have permission, please log in again' /* new */
      } else {
       res = "Oh, I don't know what the error is~~"; /* new */
    }

    return (res); /* new */
   }
}

Complete request service code

/**
  ******************************************************************************************************************************************
  * @App: test
  * @author: isiico
  * @type: service
  * @src: services/
  *
  * @descriptions:
  * Requested Service
  *
  ******************************************************************************************************************************************
  */
// Angular Core
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

// rxjs
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';

@Injectable()
export class RequestService {
  private setTimeout:number = 3000; // Default timeout
  constructor(private http:HttpClient) {
  }

   /** Add the Authorization property */
   private addAuthorization(options:any):void {
    options['headers'] = {
       'Authorization': '1drf5dg4d7s4w7z',
    };
   }
  
   /** Get data
     * param: url string required, requested url
     * time number can not be filled in. The requested timeout time. If not filled in, the default is setTimeout
     * return: Observable HttpClient get request, the value type returned after the request is any
     **/
   public getData(url, time = ):Observable<any> {
    let thiUrl = url; // The url used    let options = {}; // Requested settings    let thisTime = time; // Timeout time used    (options); // Add Authorization parameter in the request header    return (thiUrl, options)
       .timeout(thisTime)
       .catch() // Handle error information (must be placed between timeout and map)       .map(res => (res));
   }

   /** Processing of return data
     * param: data any required, data to be processed
     * return: res any Return the processed value
     **/
   private resFun(data:any):any {
    let thisData:any = data; // Values ​​to be processed    let res:any; // Final value
    // When status is 200    if (thisData['status'] == 200) {
       res = thisData['data']; // Assign the final value    } else {
    // When status is not 200      let err = thisData['msg']; // error message      throw new Error(err); // Throw an error    }
    return res; // Return the final value   }

  /** Handling of request error information
     * param: err any Required, error information to be processed
     * return: res string Processed result
     **/
   public httpErrorFun(err:any):string {
    let res:string = ''; // The processed result    let data:any = err; // Values ​​to be processed
    /** When an error message is returned in the background */
    if (('error') && ('message')) {
       res = ;

     /** When the background does not return an error message only has an error name */
    } else if (('name')) {
       let errName = ;

     /** Request timeout */
     if (errName == 'TimeoutError') {
      res = 'Sorry, the request timed out';
     }

     /** Backend return when unauthorized */
    } else if (data == "Unauthorization") {
       res = 'You do not have permission, please log in again';
      } else {
       res = "Oh, I don't know what the error is~~";
    }

    return (res);
   }
}

summary

So far, we have completed a request service that meets basic needs and can be used publicly. Next, let’s see how to call it in the component.

Call

We have a component called list. We want to call the get request. The request successfully displays data, the request fails, and the error message is displayed.

/**
  ******************************************************************************************************************************************
  * @App: test
  * @author: isiico
  * @type: component
  * @src: components/
  *
  * @descriptions:
  * list component
  *
  ******************************************************************************************************************************************
  */
// Angular Core
import { Component, OnInit } from '@angular/core';

// Services
import { RequestService } from "../services/";

@Component({
 moduleId: ,
 templateUrl: ''
})

export class ListComponent implements OnInit {
  listApi = '/assets/mock-data/'; // List api address  list:Array<any>; // List data (type is array)  listErrMsg: string = ''; // Error message for list request  
  constructor(private req: RequestService) {
  }
  
  /** Get list */
  getList(){
     = ''; // Clear the error message
    // Send a request    ()
       .subscribe(
      res=>{
      // Request succeeded         = [];
         = res;
       },err=>{
      // Request failed         = [];
         = err;
     })

   }
  
  ngOnInit() {
    ();
   }
}

Please complete the display of the page yourself!

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.