资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

angular8封装http服务的方法

这篇文章将为大家详细讲解有关angular8封装http服务的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

网站建设、成都网站制作服务团队是一支充满着热情的团队,执着、敏锐、追求更好,是创新互联的标准与要求,同时竭诚为客户提供服务是我们的理念。创新互联公司把每个网站当做一个产品来开发,精雕细琢,追求一名工匠心中的细致,我们更用心!

HttpClientModule

要在angular里使用http服务必须先在app.module.ts里导入HttpClientModule模块,不然会报错。

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 { }

封装http

根据angular的官网,请求返回的是数据的 Observable 对象,所以组件要订阅(subscribe)该方法的返回值。

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);
  }
}

这里贴上get、post两种的方式的例子,其他如delete这些就不展示了,一样的原理。

细节

稍微说一下里面的细节:

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

这里返回的是Observable<{}> ,并通过pipe管道处理请求异常,异常的处理在最下面的handleError 方法里。

使用

// 引入封装好的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);         // 失败
    }
  );
}

这是一个具体的get请求service,testGet定义里三个参数,一个是请求地址,还有成功的回调与失败的回掉。
subscribe订阅observable 对象。

在component里使用

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

关于“angular8封装http服务的方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


分享标题:angular8封装http服务的方法
转载源于:http://cdkjz.cn/article/jescsj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220