我正在尝试从API获取数据并将其绑定到我的“ headline”属性,如下面的代码所示。但是我在“回调”函数中写的是: this.headline = res;
不起作用,标题没有限制。 但是,如果我将相同的代码放入fetchData方法中,它将起作用!但是对我来说似乎没有区别吗? 我是Typescript的新手,我在做什么错了?
sp::panel.gridplot
答案 0 :(得分:1)
您需要使用箭头功能,以便在发生回调时捕获this
。
ngOnInit() {
var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
this.fetchData(headurl, (res) => {
this.headline = res;
});
}
更好的设计是将Observable
返回给调用方,而不是将回调传递给被调用的方法,而是让调用方决定如何处理结果。
ngOnInit() {
var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
this.fetchData(headurl).subscribe((res) => {
this.headline = res;
});
}
fetchData(url) : Observable<News> {
return this.http.get<News>(url);
}
答案 1 :(得分:1)
箭头函数从声明上下文中捕获this
,而常规函数则没有,this
依赖于调用者(基本上,调用者决定向该函数发送什么this
)
使用noImplicitThis
或strict
(尽管严格打开许多选项)编译器选项可以避免此类错误。
要解决此特定问题,请在第一次调用时使用箭头功能:
ngOnInit() {
var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
this.fetchData(headurl, (res) => {
this.headline = res;
});
}