httpClient GET return 类型

httpClient GET return type

如果您查看 getData() 方法,它会显示 this.http.get<Post><Post> 是否正在指定 return 类型、检查响应类型或转换返回的内容

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

    // ...

    constructor(private http: HttpClient) {}

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

这是编译器和您选择的 IDE 的类型提示。不会检查类型。

来自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.