2016-03-14 8 views
0

我在打字稿創建了一個簡單的類使用:Angular2/Ionic2 /打字稿「雙向」結合未更新,如果我在異步函數參照

export class LoginInformation { 

    private _UserName: string; 

    public get userName(): string { 
     return this._UserName 
    } 

    public set userName(v: string) { 
     this._UserName = v; 
    } 
} 

然後我可以實例化類:

private _LoginInformation: LoginInformation; 
this._LoginInformation = new LoginInformation(); 

(也實現getter和setter),然後分配一個值

this.loginInformation.userName = "User1"; 

現在我可以使用對象的我的HTML:

<ion-item> 
    <ion-input type="text" placeholder="Name" [(ngModel)]="loginInformation.userName"></ion-input> 
</ion-item> 

現在我可以改變我的對象的屬性

this.loginInformation.userName = "User2"; 

和屏幕以預期的方式更新。即使我設置:

var self: LoginInformation = this.loginInformation; 
self.userName = "User3"; 

一切都OK。但是,如果我使用異步功能(例如從應用程序首選項 - 插件獲取值)

this._AppPreferences.fetch(
    (value) => { 
     self.userName = "User4"; 
    }, 
    (error) => { 
     alert("Error loading Configuration: " + error); 
    }, 
    "LoginInformation"); 

屏幕上的值不會更新。我認爲參考作業

self: LoginInformation = this.loginInformation 

應該以預期的方式工作。但似乎缺少一些東西。

任何想法我做錯了什麼?

+0

我想你嘗試再次給予相同的參考,這就是爲什麼它沒有改變...嘗試克隆/複製loginInformtaion。 – eesdil

+0

'this._LoginInformation'或'this.loginInformation',這是什麼? 'fetch()'如何工作?它是否在Angular區域內部調用?如果不是,請嘗試添加'ApplicationRef.tick()',https://angular.io/docs/ts/latest/api/core/ApplicationRef-class.html,強制更改檢測運行。 –

回答

1

你並不需要使用self.userName,你應該能夠使用this.userName因爲你是在一個箭頭功能:

this._AppPreferences.fetch(
    (value) => { 
     this.userName = "User4"; 
    }, 
    (error) => { 
     alert("Error loading Configuration: " + error); 
    } 
); 
0

不要自行實例化的服務。你可能最終有幾個實例,而不是一個單身。使用NG2的依賴注入爲你自動做到這一點!

import { Injectable } from '@angular/core'; 
@Injectable() 
export class LoginInformation { 

    private _UserName: string; 

    public get userName(): string { 
     return this._UserName 
    } 

    public set userName(v: string) { 
     this._UserName = v; 
    } 
} 



import { Component }from '@angular/core'; 
import { LoginInformation } from './loginInformation.service'; 

@Component() 
export class YourApp { 
    constructor(_loginInformation: LoginInformation){ 

    } 

}