创建Angular的Http服务

一、准备工作

要想使用HttpClient,就要先导入Angulat的HttpClientModule,基本上都是在根模块AppModule中导入,

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

二、创建一个服务

在服务对应位置打开命令行使用命令ng g service my-data,生成一个对应的文件,并HttpClient服务注入成一个应用类的依赖项

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class MyDataService{
  constructor(private http: HttpClient) { }
}

 HttpClient服务为所有工作都使用了可观察的对象。你必须导入范例代码片段中出现的 RxJS 可观察对象和操作符

import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

三、定义方法

在服务中封装获取数据的方法和定义请求错误的处理方法

 // 获取字段方案
    getFieldScheme(fieldScheme: string): Observable<any> {
        // 基础地址
        const baseUrl = '/field/scheme/selectSchemeByIdentifier';
        // 拼接完整的URL
        const url = baseUrl + '/' + fieldScheme;
        return this.http.get(url).pipe(retry(3), catchError(this.handleError));
    }

    // 获取界面方案
    getScheme(scheme: string): Observable<any> {
        // 基础地址
        const baseUrl = 'system/scheme/selectSchemeByPermission';
        // 拼接完整的URL
        const url = baseUrl + '/' + scheme;
        return this.http.get(url).pipe(retry(3), catchError(this.handleError));
    }

    private handleError(error: HttpErrorResponse) {
        if (error.status === 0) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error);
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong.
            console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
        }
        // Return an observable with a user-facing error message.
        return throwError('Something bad happened; please try again later.');
    }

四、调用方法

在所需要获取数据的模块下引入服务,在调用方法后记得使用subscribe()进行激活,否则不会发送请求,在subscribe中使用箭头函数拿到返回的数据。

import { MyDataService } from '../../services/my-data.service';


constructor(private myDataService: MyDataService) {}

    // 获取方案
    public getScheme() {
          this.myDataService.getScheme('0o0686uxtje').subscribe(result => {
            if (result.code === 1) {
                console.error(result.msg);
            } else {
                console.log(result.data);
            }
        });
        this.myDataService.getFieldScheme('bv80a5enhcp').subscribe(result => {
            if (result.code === 1) {
                console.error(result.msg);
            } else {
                console.log(result.data);
            }
        });
    }

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值