Home >Web Front-end >JS Tutorial >How to encapsulate Angular network requests
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.this.http.post(url, param, config).subscribe( (res) => { //...请求成功 }, (err) => { //...请求失败 }, () => { //...请求完成 } );
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; }
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(); } } ); }
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) } }
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
Recommended reading:
How to use nodejs express to configure a self-signed https serverHow to build a small program with mpvueThe 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!