使用Angular的StackExchange API

时间:2018-04-05 21:27:58

标签: angular rest api

我尝试显示来自此网站的问题,但在控制台中收到错误: 错误TypeError:预期的对象 错误上下文[对象]

这是我的服务:

constructor(private _http: HttpClient) {}

searchUrl: string = "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=";

getSearchResults(searchQuery: string): Observable<searchResultsFromAPI[]> {
    return this._http.get<{items: any[]}>(`${this.searchUrl}${searchQuery}&site=stackoverflow`).map(data=>data.items);
}
}

组件:

constructor (private getSearchService: StackSearchService) { }

objectKeys = Object.keys;

searchItem = "";
questionsList: searchResultsFromAPI[];

getSearchResults(): void {
       this.getSearchService.getSearchResults(this.searchItem).subscribe(questions => this.questionsList = questions);
   console.log(this.searchItem);
}

在组件视图中,我只需调用getSearchResults(),然后点击搜索按钮。

我做错了什么?

由于

1 个答案:

答案 0 :(得分:1)

我解决了。我没有在API中返回API返回的正确类型。所以我再次看了API,这就是我现在的工作方式,并且有效:

return this._http.get<{has_more: boolean, items: any[], quota_max: number, quota_remaining: number}>