首页 > 解决方案 > 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);
    }

标签: javascriptangulartypescript

解决方案


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


推荐阅读