httpClient GET return type

时间:2018-08-22 13:50:58

标签: angular angular-httpclient

If you take a look to the getData() method it says this.http.get<Post>. Is the <Post> is specifying the return type, checking the response type, or casting what's coming back

interface Post {
      title: string;
      body: string;
    };

    // ...

    constructor(private http: HttpClient) {}

    getData() {
      this.http.get<Post>(this.url).subscribe(res => {
        this.postTitle = res.title;
      });
    }

1 个答案:

答案 0 :(得分:6)

It's a type hint for the compiler and your IDE of choice. The type will not be checked.

From the documentation:

The HttpClient.get() method parses the JSON server response into the anonymous Object type. It doesn't know what the shape of that object is.

You can tell HttpClient the type of the response to make consuming the output easier and more obvious.