Home Web Front-end JS Tutorial How to encapsulate Angular network requests

How to encapsulate Angular network requests

May 28, 2018 pm 12:00 PM
angular network ask

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to adjust MTU size on Windows 11 How to adjust MTU size on Windows 11 Aug 25, 2023 am 11:21 AM

If you're suddenly experiencing a slow internet connection on Windows 11 and you've tried every trick in the book, it might have nothing to do with your network and everything to do with your maximum transmission unit (MTU). Problems may occur if your system sends or receives data with the wrong MTU size. In this post, we will learn how to change MTU size on Windows 11 for smooth and uninterrupted internet connection. What is the default MTU size in Windows 11? The default MTU size in Windows 11 is 1500, which is the maximum allowed. MTU stands for maximum transmission unit. This is the maximum packet size that can be sent or received on the network. every support network

WLAN expansion module has stopped [fix] WLAN expansion module has stopped [fix] Feb 19, 2024 pm 02:18 PM

If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

How to solve win11 DNS server error How to solve win11 DNS server error Jan 10, 2024 pm 09:02 PM

We need to use the correct DNS when connecting to the Internet to access the Internet. In the same way, if we use the wrong dns settings, it will prompt a dns server error. At this time, we can try to solve the problem by selecting to automatically obtain dns in the network settings. Let’s take a look at the specific solutions. How to solve win11 network dns server error. Method 1: Reset DNS 1. First, click Start in the taskbar to enter, find and click the "Settings" icon button. 2. Then click the "Network & Internet" option command in the left column. 3. Then find the "Ethernet" option on the right and click to enter. 4. After that, click "Edit" in the DNS server assignment, and finally set DNS to "Automatic (D

Fix 'Failed Network Error' downloads on Chrome, Google Drive and Photos! Fix 'Failed Network Error' downloads on Chrome, Google Drive and Photos! Oct 27, 2023 pm 11:13 PM

What is the "Network error download failed" issue? Before we delve into the solutions, let’s first understand what the “Network Error Download Failed” issue means. This error usually occurs when the network connection is interrupted during downloading. It can happen due to various reasons such as weak internet connection, network congestion or server issues. When this error occurs, the download will stop and an error message will be displayed. How to fix failed download with network error? Facing “Network Error Download Failed” can become a hindrance while accessing or downloading necessary files. Whether you are using browsers like Chrome or platforms like Google Drive and Google Photos, this error will pop up causing inconvenience. Below are points to help you navigate and resolve this issue

Fix: WD My Cloud doesn't show up on the network in Windows 11 Fix: WD My Cloud doesn't show up on the network in Windows 11 Oct 02, 2023 pm 11:21 PM

If WDMyCloud is not showing up on the network in Windows 11, this can be a big problem, especially if you store backups or other important files in it. This can be a big problem for users who frequently need to access network storage, so in today's guide, we'll show you how to fix this problem permanently. Why doesn't WDMyCloud show up on Windows 11 network? Your MyCloud device, network adapter, or internet connection is not configured correctly. The SMB function is not installed on the computer. A temporary glitch in Winsock can sometimes cause this problem. What should I do if my cloud doesn't show up on the network? Before we start fixing the problem, you can perform some preliminary checks:

What should I do if the earth is displayed in the lower right corner of Windows 10 when I cannot access the Internet? Various solutions to the problem that the Earth cannot access the Internet in Win10 What should I do if the earth is displayed in the lower right corner of Windows 10 when I cannot access the Internet? Various solutions to the problem that the Earth cannot access the Internet in Win10 Feb 29, 2024 am 09:52 AM

This article will introduce the solution to the problem that the globe symbol is displayed on the Win10 system network but cannot access the Internet. The article will provide detailed steps to help readers solve the problem of Win10 network showing that the earth cannot access the Internet. Method 1: Restart directly. First check whether the network cable is not plugged in properly and whether the broadband is in arrears. The router or optical modem may be stuck. In this case, you need to restart the router or optical modem. If there are no important things being done on the computer, you can restart the computer directly. Most minor problems can be quickly solved by restarting the computer. If it is determined that the broadband is not in arrears and the network is normal, that is another matter. Method 2: 1. Press the [Win] key, or click [Start Menu] in the lower left corner. In the menu item that opens, click the gear icon above the power button. This is [Settings].

How to enable/disable Wake on LAN in Windows 11 How to enable/disable Wake on LAN in Windows 11 Sep 06, 2023 pm 02:49 PM

Wake on LAN is a network feature on Windows 11 that allows you to remotely wake your computer from hibernation or sleep mode. While casual users don't use it often, this feature is useful for network administrators and power users using wired networks, and today we'll show you how to set it up. How do I know if my computer supports Wake on LAN? To use this feature, your computer needs the following: The PC needs to be connected to an ATX power supply so that you can wake it from sleep mode remotely. Access control lists need to be created and added to all routers in the network. The network card needs to support the wake-up-on-LAN function. For this feature to work, both computers need to be on the same network. Although most Ethernet adapters use

How to check network connection details and status on Windows 11 How to check network connection details and status on Windows 11 Sep 11, 2023 pm 02:17 PM

In order to make sure your network connection is working properly or to fix the problem, sometimes you need to check the network connection details on Windows 11. By doing this, you can view a variety of information including your IP address, MAC address, link speed, driver version, and more, and in this guide, we'll show you how to do that. How to find network connection details on Windows 11? 1. Use the "Settings" app and press the + key to open Windows Settings. WindowsI Next, navigate to Network & Internet in the left pane and select your network type. In our case, this is Ethernet. If you are using a wireless network, select a Wi-Fi network instead. At the bottom of the screen you should see

See all articles