Angular HttpClient Typechecking Post Request's Repsonse

时间:2017-09-18 13:45:37

标签: angular angular-httpclient

是否可以使用Angular(4.3+)中的新HttpClient对POST(以及其他请求的类型)进行类型检查?官方文档(https://angular.io/guide/http#typechecking-the-response)仅提及GET请求:

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

它是否同样适用于其他类型的请求?

1 个答案:

答案 0 :(得分:2)

据我所知,确实如此。例如

interface LoginResponse {
    token: string;
}

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