gpt4 book ai didi

javascript - 具有 jQuery 函数范围问题的 Angular 2

转载 作者:行者123 更新时间:2023-11-30 16:14:57 25 4
gpt4 key购买 nike

我似乎无法在 jQuery.Post 中调用 addtoItems() 函数我需要为每家商店搜索商品,然后将所有商品推送到 this.items 数组中。也许有更简单的方法?显然我是 Angular 2 的新手。

import {
Page,
NavController,
NavParams,
Storage,
LocalStorage
} from 'ionic/ionic';
import {
CalculatorPage
} from '../calculator/calculator';

@Page({
templateUrl: 'build/pages/storelookup/storelookup.html'
})
export class StoreLookupPage {
constructor(nav: NavController, navParams: NavParams) {
this.nav = nav;
this.local = new Storage(LocalStorage);
// If we navigated to this page, we will have an item available as a nav param
this.selectedItem = navParams.get('item');
this.items = [];
}
addtoItems(itemlist, storeid, phone, city, st, address, distance) {
for (var o = 0; o < itemlist.length; o++) {
this.items = []
this.items.push(itemlist[o]);
this.items[o].storeid = storeid
this.items[o].phone = phone
this.items[o].city = city
this.items[o].st = st
this.items[o].address = address
this.items[o].distance = distance
console.log(this.items)
}
}

getItems(query) {
this.items = [];
var name = encodeURIComponent(name);
this.storelist = JSON.parse(this.local.get("stores")._result)
var i = 0;
var i1 = setInterval(function() {

this.local = new Storage(LocalStorage);
this.storelist = JSON.parse(this.local.get("stores")._result)
var storeid = Number(this.storelist[i].id);
var phone = this.storelist[i].phone;
var city = this.storelist[i].address.city;
var st = this.storelist[i].address.state;
var address = this.storelist[i].address.address1;
var distance = this.storelist[i].distance;

jQuery.post("http://www.walmart.com/store/ajax/search", {
searchQuery: "store=" + storeid + "&size=50&query=ipad&offset=0"
})
.done((data) {
var storeresult = JSON.parse(data.searchResults);
var preitems = storeresult.results.filter(isUPC);
this.addtoItems(storeresult.results, storeid, phone, city, st, address, distance); //TypeError: _this.addtoItems is not a function

console.log(this.items)
});
i++;
if (i === this.storelist.length) {
clearInterval(i1);
}
}, 1000);

}

最佳答案

使用arrow function

(x) => { ... }

代替

(x) { ... }

function (x) { ... }

then this. 总是引用当前类。否则你需要使用 .bind(...)

代码示例

.done((data) {
var i1 = setInterval(function() {

关于javascript - 具有 jQuery 函数范围问题的 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com