简体   繁体   中英

Angular 2+ HttpClient response Typescript Type

I'm using angular's httpClient, and trying to use proper typescript typing, but I'm doing something wrong. The following code gives me an error

  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]

Argument of type '(response: { url: string; }) => void' is not assignable to parameter of type '(value: Object) => void'. Types of parameters 'response' and 'value' are incompatible. Type 'Object' is not assignable to type '{ url: string; }'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Property 'url' is missing in type 'Object'. [2345]

If I change it to response: object... then it complains that

" Property 'url' does not exist on type 'object'."

What is the correct way of doing this?

Normally, I expect some type of object back from my post. I define that object with an interface, like this:

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

I then use that interface as a generic parameter on the post:

  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)
      );
  }

Notice the Observable<Product> as the return type and the this.http.post<Product> in the call.

As per best practices, I subscribe to the observable in the component:

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

With all of that said ... is this what you are asking about? Or are you trying to get the url of the created item from the response?

If so, then this may also help: Read response headers from API response - Angular 5 + TypeScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM