首页 > 解决方案 > “HttpParams”类型的参数不能分配给“URLSearchParams”类型的参数

问题描述

我正在更新一个应用程序以使用来自 Angular 4 的 Angular 8。我以前从未真正使用过 Angular,并且我遇到了几个弹出错误。我有这个错误出现:

Argument of type 'HttpParams' is not assignable to parameter of type 'URLSearchParams'.

当试图运行这个

queryBatches(searchParams: HttpParams): Promise<PaginatedData> {
      return this.authService.generateAuthHeader({'Content-Type': 'application/json'}, searchParams).then(options => {
        return this.http.get(endpoints.query.batches({}), options)
          .map(response => {
            return new PaginatedData(response.json(), Batch);
        }).toPromise();
      });
    }

这是我要导入的

import {Injectable} from '@angular/core';
import {PaginatedData} from '../../models/common';
import {Batch} from '../../models/batch/batch.model';
import {AuthService} from '../auth/auth.service';
import endpoints from '../endpoints';
import {HttpParams} from '@angular/common/http'
import {Http, URLSearchParams} from '@angular/http';
import {BatchMismatch} from '../../models/batch/batch-mismatch-model';
import {BatchMismatchReviewer} from '../../models/batch/batch-mismatch-reviewer-model';
import {BatchMisMatchReload} from '../../models/batch/batch-mismatch-reload-model';

对此问题的任何帮助将不胜感激

编辑:我还应该以我最初没有编写此代码作为开头。

生成AuthHeader:

generateAuthHeader(additionalHeaders?: {[index: string]: any}, searchParams?: URLSearchParams): Promise<RequestOptions> {
    if (this.cookieService.get('auth-cookie')) {
      let authCookie = JSON.parse(this.cookieService.get('auth-cookie')) as AuthCookie;
      const headers = new Headers({'Authorization': `Bearer ${authCookie.token}`});
      if (additionalHeaders) {
        for ( let headerValue of Object.keys(additionalHeaders)) {
          headers.append(headerValue, additionalHeaders[headerValue]);
        }
      }
      const options =  new RequestOptions({headers: headers, params: searchParams});
      return Promise.resolve(options);
    }
    else {
      return Promise.reject({status: 401});
    }
  }

标签: angulartypescript

解决方案


错误正是它所说的。

generateAuthHeader的第二个参数应该是 type 的URLSearchParams,但是你传递给它一个 type 的对象HttpParams

现在,无论它是否真的是那种类型,你都需要控制台日志来查看参数。如果只是输入错误,请更新类型以使其匹配。如果queryBatches确实收到了一个HttpParams对象,那么您将需要弄清楚如何制作一个新对象以传递给generateAuthHeader


推荐阅读