[英]What's wrong with my code with Angular and Typescript?
I'm trying to get data from API and bind it to my "headline" property as shown in below code. 我正在尝试从API获取数据并将其绑定到我的“ headline”属性,如下面的代码所示。 But what I wrote in the "callback" function: this.headline = res;
但是我在“回调”函数中写的是:this.headline = res;
does not work, the headline is not bound. 不起作用,标题没有限制。 However, if I put the same code in the fetchData method, it works!
但是,如果我将相同的代码放入fetchData方法中,它将起作用! But to me it seems there is no difference?
但是对我来说似乎没有区别吗? I'm new to Typescript, what am I doing wrong here?
我是Typescript的新手,我在这里做错了什么?
import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
public news: News[];
public headline: News;
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
}
ngOnInit() {
var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
this.fetchData(headurl, function (res) {
//this code does not work
this.headline = res;
});
}
fetchData(url, callback) {
this.http.get<News>(url).subscribe(result => {
callback(result);
//this code works!
this.headline = result;
}, error => console.error(error));
}
}
interface News {
SourceId: string;
SourceName: string;
Author: string;
Title: string;
Description: string;
Url: string;
UrlToImage: string;
PublishedAt: string;
}
You need to use an arrow function so that this
is captured when the callback occurs. 你需要让使用箭头功能
this
回调时发生被捕获。
ngOnInit() {
var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
this.fetchData(headurl, (res) => {
this.headline = res;
});
}
A better design would be to return an Observable
to the caller instead of passing a callback to the the method being called and let the caller decide how to handle the result. 更好的设计是将
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);
}
An arrow function captures this
from the declaration context while a regular function does not and has this
dependent on the caller (basically the caller decides what this
to send to the function) 箭头功能捕捉
this
从声明上下文而普通功能不并拥有this
取决于调用者(基本主叫方决定什么this
发送到功能)
Use the noImplicitThis
or strict
(although strict turn on a lot more options) compiler options to avoid such errors. 使用
noImplicitThis
或strict
(尽管严格打开许多选项)编译器选项可避免此类错误。
To fix this particular issue also use an arrow function for the first call : 要解决此特定问题,请在第一次调用时使用箭头功能:
ngOnInit() {
var headurl = this.baseUrl + "api/News/Headline?country=us&category=business";
this.fetchData(headurl, (res) => {
this.headline = res;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.