我有一种从链接读取数据的方法。我试图访问宽度大于600但警告的图像(this.images.length);这总是给零,这是在我的呼叫回叫叫做
之前执行的 readLink(url: string) {
this.isBusy = true;
this._http.get(`${this._helper.baseURL}/api/post/readlink?url=${encodeURIComponent(url)}`)
.subscribe(
data => {
this.processResponse(data, url);
},
(err: HttpErrorResponse) => {
}
);
}
处理请求数据的方法
processResponse(result, url) {
if (result.images != null && result.images.length > 0) {
result.images.forEach(el => {
this.getMeta(el, function (res) {
this.images.push(res);
this.currentImage = this.images[0];
});
});
}
alert( this.images.length); // this always give zero and this was executed before my call bakc
}
此回调功能可获取有效图像
getMeta(url, callback) {
const img = new Image();
img.src = url;
img.onload = function () {
if (img.width > 260 && img.height > 150) {
callback(url);
}
};
}
答案 0 :(得分:2)
如果您想在函数中使用this
,请不要使用function () {
this.getMeta(el, function (res) {
应该是
this.getMeta(el, (res) => {
否则this
将不会指向定义函数的类实例。
另见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions