Chrillewoodz
Chrillewoodz

Reputation: 28318

Angular - Unable to set http response types properly

I've got a service which exposes some functions that uses HttpClient requests, one of them being a post:

post<T>(url: string, data: any, params?: {[key: string]: any}): Observable<HttpEvent<T>> {
  return this.http.post<T>(this.host + url, data, this.getRequestOptions(params));
}

The important thing here is the return signature Observable<HttpEvent<T>>.

Then when I call the function I get two problems:

this.api.post<string>('/tokens', credentials).subscribe((token: string) => {});

The first problem is that I can't pass in a type with <string> due to an lint error saying:

Expected 0 type arguments but got 1

The second problem is that all data in the responses becomes the type HttpEvent<T>, instead of what I send in, in this example it should be of type string.

So in the example above I get this error:

Argument of type '(token: string) => void' is not assignable to parameter of type '(value: HttpEvent<{}>) => void'. Types of parameters 'token' and 'value' are incompatible. Type 'HttpEvent<{}>' is not assignable to type 'string'. Type 'HttpProgressEvent' is not assignable to type 'string'.

How can I fix this so that I can set my response type properly?

Upvotes: 1

Views: 1750

Answers (1)

Anton Lee
Anton Lee

Reputation: 694

Try this:

 post<T>(url: string, data: any, params?: {[key: string]: any}): Observable<T> {
            return this.http.post<T>(this.host + url, data, this.getRequestOptions(params)).map((res: T) => res);
        }

Upvotes: 1

Related Questions