0

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?

Vikas
  • 11,859
  • 7
  • 45
  • 69
Asool
  • 13,031
  • 7
  • 35
  • 49
  • What are you expecting back from the post? This article may help: https://www.concretepage.com/angular/angular-httpclient-post, especially this section: HttpClient.post and Response Type – DeborahK Dec 11 '18 at 17:20

1 Answers1

0

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

DeborahK
  • 57,520
  • 12
  • 104
  • 129