一、准备工作
要想使用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);
}
});
}