2016-01-18 65 views
4

我試圖從DB中檢索數據並將其設置爲作用域2中的作用域變量。我不知道爲什麼。我試過超時區域。氣東西,承諾事情。我真的不知道他們是什麼,所以我無法使用它..請幫助我弄清楚這一點。Angular2中的回調函數中的作用域變量的訪問值

//in service.ts 
    listFriends(callback) { 
    result_data = []; 

    db.transaction(function(tx) { 

     tx.executeSql('SELECT * from mytable', [], function(tx, results) { 

      length = results.rows.length; 

      for (i = 0; i < length; i++) { 

       //console.log(results.rows.item(i)); 
       result_data.push(results.rows.item(i)) 
      } 
      callback(result_data); 

     }, null); 

    }); 

} 
//in component.ts 
public allmyFriends: any; 
public self = this; 
public test; 
constructor(myFriendService: MyFriendService) { 



    this.myFriendService = myFriendService; 
    this.myFriendService.listFriends((response) => { 
     //trying to set value to the scope variable.but not working 
     this.test="test working"; 
     //same as above 
     this.allmyFriends = response; 
     //getting the response from the service successfully 
     console.log("in list" + this.allmyFriends); 

    }); 
    } 

回答

4

當你說你嘗試了區域。你究竟是什麼意思?你注入NgZone並在其中執行代碼嗎?

這個問題可以給你一些提示:View is not updated on change in Angular2

從哪裏得到您的地圖實例。如果它在區域外實例化,則Angular2將無法檢測到mapLatitudeInput屬性的更新。

你可以嘗試這樣的事情:

export class MapComponent { 
    constructor(ngZone:NgZone) { 
    this.ngZone = ngZone; 
    } 

    someMethod() { 
    this.myFriendService.listFriends((response) => { 
     this.ngZone.run(() => { 
     this.test="test working"; 
     this.allmyFriends = response; 
     console.log("in list" + this.allmyFriends); 
     }); 
    }); 
    } 

這個問題可能也涉及到你的問題:Angular2 child property change not firing update on bound property

希望它可以幫助你, Thierry

+0

OMG! NgZone。 run()像魅力一樣工作。非常感謝你@thierry。我用過這個。 _ngZone.runOutsideAngular(),這就是爲什麼它不起作用。你知道嗎? – Nishanthd

+1

酷!很高興聽到;-)'runOutsideAngular'方法用於在觸發Angular2變化檢測的區域之外的Angular2之外執行一些處理。所以這種行爲似乎很正常...... –

相關問題