getBooks(): Observable<Array<Books>> {
return this.http
.get<{ items: Books[] }>(
'https://www.googleapis.com/books/v1/volumes?maxResults=5&orderBy=relevance&q=oliver%20sacks'
)
.pipe(map((books) => books.items || []));
}
尝试理解这里的打字稿语法...
.get<{ items: Books[] }>(
这是否意味着它首先获取 url 并对其执行
map
过滤运算符,然后返回一个仅包含具有 items
接口的 Books[]
属性的对象?
它只是将 HTTP GET 调用的返回主体类型断言/转换为
{ items: Books[] }
。它不会添加任何实际类型安全性。相当于:
getBooks(): Observable<Array<Books>> {
const res: { items: Books[] } = this.http
.get(
'https://www.googleapis.com/books/v1/volumes?maxResults=5&orderBy=relevance&q=oliver%20sacks'
);
return res..pipe(map((books) => books.items || []));
}