Home >Web Front-end >JS Tutorial >How to encapsulate http service in angular8

How to encapsulate http service in angular8

青灯夜游
青灯夜游forward
2021-03-12 09:44:062425browse

This article will introduce to you the angular8 method of encapsulating http services. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to encapsulate http service in angular8

Related recommendations: "angular tutorial"

HttpClientModule

To use the http service in angular, you must first import the HttpClientModule module in app.module.ts, otherwise an error will be reported.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
// 导入关键模块
import { HttpClientModule } from '@angular/common/http';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Encapsulate http

According to angular’s ​​official website, the request returns the Observable object of the data, so the component must Subscribe(subscribe) The return value of this method.

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  private http: any;

  constructor(private Http: HttpClient) {
    this.http = Http;
  }

  // get方法
  public get(url: string, options?: Object, params?: Object): Observable<{}> {
    let httpParams = new HttpParams();
    if (params) {
      for (const key in params) {
        if (params[key] === false || params[key]) {
          httpParams = httpParams.set(key, params[key]);
        }
      }
    }
    return this.http.get(url, { headers: options, params: httpParams }).pipe(catchError(this.handleError));
  }
  
  // post方法
  public post(url: string, body: any = null, options?: Object): Observable<{}> {
    return this.http.post(url, body, options).pipe(catchError(this.handleError));
  }

  // post表单
  public postForm(url: string, body: any = null, options?: Object): Observable<{}> {
    let httpParams = new HttpParams();
    if (body) {
      for (const key in body) {
        if (body[key] === false || body[key]) {
          httpParams = httpParams.set(key, body[key]);
        }
      }
    }
    return this.http.post(url, httpParams, options).pipe(catchError(this.handleError));
  }

  /**
   * 处理请求失败的错误
   * @param error HttpErrorResponse
   */
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    console.log(error);
    return throwError(error.error);
  }
}

Here are examples of get and post. Others such as delete will not be shown. The principle is the same.

Details

Let’s talk about the details:

return this.http.post(url, httpParams, options ).pipe(catchError(this.handleError));

What is returned here is Observable<{}>, and request exceptions are processed through the pipe pipeline. Exceptions The processing is in the handleError method at the bottom.

Use

// 引入封装好的http服务
constructor(private http: HttpService) { }

/**
   * 测试get方法
   * @param successCallback 成功的回调
   * @param failCallback 失败的回调
   */
public testGet(url: string, successCallback?: Function, failCallback?: Function) {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json; charset=UTF-8'
    })
  };

  this.http.get(url, httpOptions.headers).subscribe(
    (res: any) => {
      successCallback(res); // 成功走sucessCallback
    }, (err: HttpErrorResponse) => {
      failCallback(err);         // 失败
    }
  );
}

This is a specific get request service, testGetThere are three parameters in the definition, one is the request address, and success callback and failure callback.
subscribe subscribes to the observable object.

Use in component

this.testService.testGet('url', (res:any) => {}, (err:any) =&gt ;{});

Summary

Angular encapsulation of http requests is not difficult, and the official website also explains it clearly.

Personally, I think the most important thing is the idea of ​​encapsulating services, and why does Angular differentiate between component services?

An important reason is that it hopes that data display logic and data access logic are separated, and the data that the component needs to display on the page is delegated to a certain Get a service! This enables high code reuse.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of How to encapsulate http service in angular8. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete