2016-02-27 88 views
1

我似乎無法在jQuery.Post 內調用addtoItems()函數我需要爲每個商店搜索項目,然後將所有內容都推送到this.items數組中。也許有一個更簡單的方法? 很顯然,我是新來的角2Angular 2與jQuery功能範圍問題

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

變化進行功能to'.done((數據)=> {...})'。 – Sasxa

回答

1

使用arrow function

(x) => { ... } 

,而不是

(x) { ... } 

function (x) { ... } 

then this.總是指當前類。 否則,你就需要使用.bind(...)

例子從您的代碼

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

非常感謝,這解決了我的問題。 – YourEvilMonk