【问题标题】:Angular 2 and typescript argument of type response is not assignableAngular 2 和 typescript 类型响应的参数不可分配
【发布时间】:2018-08-15 18:50:34
【问题描述】:

我有一个角度服务,其值定义为:

private client_comments  = new BehaviorSubject([]);

我正在尝试使用来自 http 调用的响应来设置值,但我看到了:

“响应”类型的参数不能分配给“任何[]”类型的参数。 “响应”类型中缺少属性“长度”

...我的电话看起来像:

this.http.get(final_url, o).subscribe( comments => {
  this.client_comments.next(comments)
})

我应该如何设置响应的类型,以便它知道它将是一个数组?

【问题讨论】:

  • 希望我知道为什么这被否决了吗?

标签: angular typescript http


【解决方案1】:
this.client_comments.next(comments.json() as YourType[])

您还应该设置主题,使其也输入为YourType[]

【讨论】:

    【解决方案2】:

    如果您使用@angular/http 包(已弃用),https://angular.io/api/http/Http

    像这样使用它:

    this.http.get(final_url, o)
        .map((res: Response) => res.json())
        .subscribe( comments: any[] => {
            this.client_comments.next(comments)
        });
    

    如果您使用@angular/common/http 包(这是推荐的包),https://angular.io/guide/http

    像这样使用它:

    this.http.get<any[]>(final_url, o)
        .subscribe( comments: any[] => {
            this.client_comments.next(comments)
        });
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 1970-01-01
      • 2023-03-19
      • 2019-05-12
      • 2021-03-08
      • 2021-10-17
      • 2020-03-26
      • 2019-01-03
      • 1970-01-01
      相关资源
      最近更新 更多