温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

angular8封装http服务的方法

发布时间:2021-03-12 10:22:47 来源:亿速云 阅读:250 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关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服务的方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI