带有 jQuery 函数范围的 Angular 2

Angular 2 with jQuery function scope issue

本文关键字:Angular 范围 jQuery 函数 带有      更新时间:2023-09-26

我似乎无法在 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);
    }

使用箭头函数

(x) => { ... }

而不是

(x) { ... }

function (x) { ... }

this.始终引用当前类。否则,您需要使用.bind(...)

代码中的示例

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