文章内容
2019/5/8 10:27:44,作 者: 黄兵
Angular HttpClient get 提交方式
最近在学习Angular HttpClient的Get提交方式,首先看httpClient的源代码:
/** * Constructs a `GET` request that interprets the body as a JSON object and * returns the response body as a JSON object. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * * @return An `Observable` of the response body as a JSON object. */ get(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: 'body'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }): Observable
其中url必须,其他的一些可选参数有header,observe,params等。
返回的是一个Observable。
具体写法如下:
confirmEmail(userId, code): Observable<any>{ // Initialize Params Object let params = new HttpParams(); // Begin assigning parameters params = params.append('userId', userId); params = params.append('code', code); return this.http.get('/api/identity/ConfirmEmail', { headers: new HttpHeaders().set('Content-Type', 'application/json'), params }).pipe(map((response: Response) => { return response; }), catchError((error: any) => { return throwError(error); })); }
传入两个参数userId和code,之后增加了header和param。
同时需要导入HttpHeaders:
import {HttpClient, HttpHeaders} from '@angular/common/http';
返回一个Observable,以及错误处理。
参考资料:
1、Angular 4 HttpClient Query Parameters
黄兵个人博客原创。
评论列表