Angular 2与jQuery函数范围问题

时间:2016-02-27 18:16:51

标签: javascript jquery ionic-framework angular ionic2

我似乎无法调用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);

    }

1 个答案:

答案 0 :(得分:2)

使用arrow function

(x) => { ... }

而不是

(x) { ... }

function (x) { ... }

然后this.总是指当前的类。 否则,您需要使用.bind(...)

代码中的示例

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