基础版
直接在url上拼接参数
httpOptions = {
headers: new HttpHeaders()
.set('content-Type', 'application/json')
.set('Authorization', this.global.token)
};
// 获取书本信息
getBooks(page: number = 1, size: number = 10, keywords: string = ''): Observable<Result> {
return this.http.get<Result>('api/book' + `?currentPage=${page}&pageSize=${size}&author=${author}&book=${book}&type=${type}`, this.httpOptions);
}
存在问题
直接拼接参数会出现编码问题
例如: page=1 size=10 author=’’ book= ‘’ type=’’
请求的地址:
得到的数据:
改良版
headers = new HttpHeaders()
.set('content-Type', 'application/json')
.set('Authorization', this.global.token);
httpOptions = {
headers: this.headers
};
// 获取书本信息
getBooks(
page: number = 1,
size: number = 10,
author: string = '',
book: string = '',
type: string = ''
): Observable<Result> {
const params = new HttpParams()
.set('currentPage', String(page))
.set('pageSize', String(size))
.set('author', author)
.set('type', type)
.set('book', book);
return this.http.get<Result>(
'api/book',
{
params,
headers: this.headers
},
);
}
改善的地方:
请求的地址
获取的数据
改良版和基础版的区别:
-
改良版不再用拼接字符串的形式去请求
改用angular妈妈给我们准备好的 HttpParams工具去拼接参数
注意的问题:
Request请求只能携带两个参数(请求地址和请求体) 例如:
this.http.get(url, {params: params, headers: headers});