Angular HttpClient Typechecking Post Request's Repsonse

237 Views Asked by At

Is it possible to use type checking for POST (and type of other requests) with the new HttpClient in Angular (4.3+) as well? The official documentation (https://angular.io/guide/http#typechecking-the-response) only mentions GET requests:

interface ItemsResponse {
  results: string[];
}

...

http.get<ItemsResponse>('/api/items').subscribe(data => {
   // data is now an instance of type ItemsResponse, so you can do this:
   this.results = data.results;
});

Does it work for other kind of requests the same way?

1

There are 1 best solutions below

0
On BEST ANSWER

To my knowledge, it does. For example

interface LoginResponse {
    token: string;
}

...
this.http.post<LoginResponse>(url, body, options).subscribe(
    data => {
        this.jwtoken = data.token;
        return 'Login successful';
    },
    err => {
        console.log(err);
    }
);