Home > Web Front-end > JS Tutorial > body text

How to encapsulate Angular network requests

php中世界最好的语言
Release: 2018-05-28 12:00:27
Original
1478 people have browsed it

This time I will show you how to encapsulate Angular network requests and what are the precautions for encapsulating Angular network requests. The following is a practical case, let's take a look.

Here I will talk about my own network request encapsulation. In a sense, angular's own network request encapsulation is very good. We don't need to add any more details, but maybe I have a little bit of it. I am a code freak and like my own style, so I have this extra thing.

Angular’s ​​network request

This is angular’s ​​own network request.

  1. url represents the network request address,

  2. param network

    Request parameter

  3. ##Network request configuration, for example: request first class
  4.  this.http.post(url, param, config).subscribe(
       (res) => {
        //...请求成功
       }, (err) => {
        //...请求失败
       }, () => {
        //...请求完成
       }
      );
    Copy after login
  5. Many times I feel that it is very troublesome to write the parameters in subscribe for every request, or it seems uncomfortable. I like it, so I usually encapsulate a new service service for myself. At the same time, a new
interface interface

is implemented for each component component that needs to make network requests. Many of them are derived from the design ideas of the Java language.

A network interfaceCreate a network interface here to complete the callback of network requests.

export interface OnHttpImp {
 onResult(result: HttpResult, code?: number): void;
 onError?(err:any): void;
 onComplete?(): void;
}
export class HttpResult {
 code?: number;
 data?: any;
 msg?: string;
}
Copy after login

The OnHttpImp interface creates three methods, namely onResult, onError and onComplete. OnComplete and onError are optional, and onResult must be implemented. The three functions here are used to complete the three callbacks of http.

Then, the above network request can be moved to the new service CommonService, and it will become like this:

 public post(url: string, param: FormData, callback: OnHttpImp, code?: number) {
  url = Config.base + url;
  const headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  this.http.post(url, param, {}).subscribe(
   (res) => {
    if (code) {
     callback.onResult(res, code);
    } else {
     callback.onResult(res);
    }
   }, (err) => {
    console.log(url + '===>' + JSON.stringify(err));
   }, () => {
    if (callback.onComplete) {
     callback.onComplete();
    }
   }
  );
 }
Copy after login

There is no need to explain the url and param here, the callback is just one An instance of OnHttpImp is used to call back the data returned by the network request to the corresponding component, so that data processing and network requests can be separated from each other. code is an identifier used to distinguish data when sending multiple requests in a component.

HttpResult is a class that returns data from network requests. It is used to facilitate data processing. It can be customized and encapsulated appropriately according to its own data return type.

Called componentLook at the code first:

export class LoginComponent implements OnInit, OnHttpImp {
 public validateForm: FormGroup;
 public username_control: AbstractControl;
 public password_control: AbstractControl;
 constructor(private fb: FormBuilder,
       private http: HttpUtil) {
 }
 ngOnInit() {
  this.validateForm = this.fb.group({
   'userName': [null, [Validators.required]],
   'password': [null, [Validators.required]],
   remember: [true],
  });
  this.username_control = this.validateForm.controls['userName'];
  this.password_control = this.validateForm.controls['password'];
 }
 _submitForm() {
  const params = new FormData();
  const md5 = new Md5();
  const password = md5.appendStr(this.password_control.value).end();
  params.set('username', this.username_control.value);
  params.set('password', password.toString());
  this.http.post('/user/login', params, this);
 }
 onResult(result: HttpResult, code?: number): void {
  //如果多个网络请求,需要传入code值,根据code值来判断请求来源
  //swthch(code){
  //  case 100:
  //  
  //  break;
  //}
  
  // 如果单个请求,直接处理请求结果。
  // console.log(result)
  
 }
}
Copy after login

The OnHttpImp object transmitted by the above http request is this, then This means that the LoginComponnt component must implement the OnHttpImp interface, and then implement the functions onResult, onError and onComplete.

In this way, the http request and data processing can be separated, and the readability and simplicity of the code will be improved. There is a big improvement.

Further encapsulation method

    You can use this that is passed in when calling the network request in the above component. A unified class MCallback is used instead to uniformly process the returned data.
  1. You can put all network requests into one service and request them by calling the method name. This can achieve the coupling of multiple network requests, but I personally think it is a bit over-encapsulated.
  2. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use nodejs express to configure a self-signed https server


How to build a small program with mpvue

The above is the detailed content of How to encapsulate Angular network requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!