【问题标题】:Angular - Argument of type 'OperatorFunction<Response, Response>' is not assignable to parameter of type 'OperatorFunction<Object, Response>'Angular - 'OperatorFunction<Response, Response>' 类型的参数不可分配给'OperatorFunction<Object, Response>' 类型的参数
【发布时间】:2021-07-02 20:49:00
【问题描述】:

在我的 Angular-12 应用程序中,我在服务中有以下代码:

 constructor(private http: HttpClient, private router: Router) {
   var currentUser = JSON.parse(localStorage.getItem('user')|| '{}');
  this.token = currentUser && currentUser.token;
}

  public getAllCountries(): Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        "Content-Type": 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, Authorization, Content-Type, Accept",
        "Authorization" : "Bearer " + this.token
      })
    };

    return this.http.get(this.apiUrl  + '/fetchCountries', httpOptions )
        .pipe(
            map((response: Response) => {
                return response;
            })
        );
  }

这一行被高亮显示:

map((response: Response) => {

返回响应;

然后我得到了这个错误:

Argument of type 'OperatorFunction<Response, Response>' is not assignable to parameter of type 'OperatorFunction<Object, Response>'.
  The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
    Type 'Object' is missing the following properties from type 'Response': headers, ok, redirected, status, and 12 more.ts(2345)

如何解决?

谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    您使用的是Response,它也非常不推荐使用,如果我没记错的话,它在我们使用Http 时被使用过,比如pre angular 版本4。 HttpClient... 它返回一个通用对象,就像错误中所说的那样。相反,您应该将数据键入接口并告诉 HttpClient 您正在接收什么。假设你得到一个数组,所以这样的东西应该可以工作:

    export interface Country {
      // whatever properties your response has
    }
    

    然后告诉 HttpClient 你期望的响应是Country 的数组。此外,您实际上并不需要map,因为您不会以任何方式修改数据......所以这就足够了:

    return this.http.get<Country[]>(this.apiUrl  + '/fetchCountries', httpOptions)
    

    请始终参考官方文档以获取最新文档:https://angular.io/guide/http

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2020-07-24
      • 2021-11-11
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多