angular8如何封装http服务


本文摘自PHP中文网,作者青灯夜游,侵删。

本篇文章给大家介绍一下angular8封装http服务的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

相关推荐:《angular教程》

HttpClientModule

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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) 该方法的返回值。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

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这些就不展示了,一样的原理。

细节

稍微说一下里面的细节:

阅读剩余部分

相关阅读 >>

解决tcp粘包问题的两种办法

AngularAngularjs、react和vue的简单对比

10个从喜到悲的Angular面试题

浅谈Angular中父子组件间怎么传递数据

浅谈Angular中如何添加和使用font awesome

聊聊Angular指令中的prelink和postlink函数

详解Angular中的路由及其用法

详解Angular中的组件交互

http状态代码是什么

浅谈Angular中的变化检测(change detection)

更多相关阅读请进入《Angular》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...