【问题标题】:Angular 2+ HttpClient response Typescript TypeAngular 2+ HttpClient 响应 Typescript 类型
【发布时间】:2019-05-12 17:18:27
【问题描述】:

我正在使用 Angular 的 httpClient,并尝试使用正确的打字稿打字,但我做错了什么。下面的代码给了我一个错误

  this.httpClient
            .post(this.loginUrlRoute, params)
            .pipe(
                retry(3),
                catchError(this.handleError.bind(this))
            )
            .subscribe((response: { url: string}) => {
                Office.context.ui.displayDialogAsync(response.url);
            });

[ts]

'(response: { url: string; }) => void' 类型的参数不是 可分配给“(值:对象)=> void”类型的参数。种类 参数“响应”和“值”不兼容。 类型 'Object' 不可分配给类型 '{ url: string; }'。 “对象”类型可分配给极少数其他类型。您的意思是改用“任何”类型吗? “对象”类型中缺少属性“url”。 [2345]

如果我将其更改为 response: object... 那么它会抱怨

" 属性 'url' 在类型 'object' 上不存在。"

这样做的正确方法是什么?

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

通常,我希望从我的帖子中回复某种类型的object。我使用接口定义该对象,如下所示:

export interface Product {
  id: number;
  productName: string;
  productCode: string;
}

然后我将该接口用作帖子上的通用参数:

  createProduct(product: Product): Observable<Product> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    product.id = null;
    return this.http.post<Product>(this.productsUrl, product, { headers: headers })
      .pipe(
        tap(data => console.log('createProduct: ' + JSON.stringify(data))),
        catchError(this.handleError)
      );
  }

注意Observable&lt;Product&gt; 作为返回类型,this.http.post&lt;Product&gt; 在调用中。

根据最佳实践,我订阅了组件中的 observable:

      this.productService.createProduct(p)
        .subscribe(
          (product: Product) => console.log(product),
          (error: any) => this.errorMessage = <any>error
        );

说了这么多……这就是你要问的吗?或者您是否尝试从响应中获取已创建项目的 url?

如果是这样,那么这也可能有所帮助:Read response headers from API response - Angular 5 + TypeScript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2018-08-15
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多