javascript - HttpParams 为调用设置 null
问题描述
将我的项目从 Angular 7 迁移到 Angular 8 后,HttpParams 和 HttpHeaders 出现问题。当我调用 API 时,未添加参数。如果有人可以帮我解决这个问题,那就太好了。
这是我定义标题和参数的方法。
fetchJson(url: string, parameters ? : any) {
this.token = this.cookieService.get('access_token');
this.contrat_token = this.cookieService.get('contrat_token');
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);
let params = new HttpParams()
params.set('search', parameters);
console.log('les headers');
console.log(headers);
console.log('params');
console.log(params.toString())
return this._http.get(url, {
headers,
params
}).pipe(map((resp: any) => {
if (resp.status === 401 || resp.status == 401 || resp.status.toString() == "401") {
this.clearCookie();
} else {
let reponse = resp;
if (reponse == -1 || reponse == "-1") {
this.router.navigate(["/"]);
}
}
return resp;
}
我在我的服务中调用这个方法如下。
getDetailThematiquePrevNext(id: string, typeBase: string) {
let URL = this.urlDecorator.urlAPIDecorate("DI", "GetDetailThematiqueHeaderPrevNext");
let params = this.urlDecorator.generateParameters({
id: id,
typeBase: typeBase,
});
return this.apiFetcher.fetchJson(URL, params);
}
解决方案
Cue 提供的原因是正确的,您需要使用链接或执行您对标头所做的操作
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);
let params = new HttpParams()
params = params = params.set('search', parameters);
更易读的写法如下
const headers = new HttpHeaders()
.append('Content-Type', 'application/json')
.append('Authorization', 'Bearer ' + this.token)
.append('contrat_token', this.contrat_token);
const params = new HttpParams().set('search', parameters);
此外,您可以删除Content-Type
标头,因为默认情况下它是 json
推荐阅读
- python - ValueError:优化器在 pytorch 中得到了一个空的参数列表
- javascript - 如何在javascript中使用正则表达式查找匹配的字符串
- javascript - 更新数组中的对象(按值匹配)
- numpy - 创建向量矩阵之间所有可能平方差的 Numpy 数组
- c# - 集合视图中所选项目的圆角
- javascript - React/JS/TS - 表格不会呈现行
- git - 如何在镜像/分叉的 git 存储库之上维护更改?
- python - 返回列表中引用索引的元素
- angular - Angular 9 *ngFor 循环跳过数组中的一些对象
- python - 需要帮助使用 pygame 实现合并排序的可视化工具