Search code examples
angularangular-httpclient

Angular HttpClient Typechecking Post Request's Repsonse


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?


Solution

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