如何在typescript中设置observable属性异步?

时间:2017-09-11 02:23:21

标签: typescript nativescript

我有几个异步获取的属性。我想将这些属性的结果绑定到我的应用程序中的视图。但是,get属性将视图模型的变量视为null。结果到达后如何绑定它们?在下面的代码中,userEmailappVersion在各自的get函数中为null / undefined。

export class AccountViewModel extends Observable {
    private _userEmail : Email;
    private _appVersion : string;

    constructor() {
        super();

        appVersion.getVersionName().then(
            (result) =>
            {
                this._appVersion = result;
                console.log(this._appVersion);
            });

        firebase.getCurrentUser().then(
            (result) => {
                this._userEmail = new Email(result.email);
            });
    }

    get userEmail(): string {
        return this._userEmail != null ? this._userEmail.Value : "";
    }

    get appVersion(): string {
        return this._appVersion;
    }

    public logout() {
        firebase.logout().then((result) => {
            Navigator.navigateTo({
                moduleName : "views/register/register",
                backstackVisible : false,
                clearHistory : true
            })
        }).catch((error) => {
            dialogs.alert({
                title: "Error",
                message: "A system error occurred trying to logout.",
                okButtonText: "Ok"
            });
        });
    }
}

1 个答案:

答案 0 :(得分:0)

Observable类有一个notifyPropertyChange方法:)

export class AccountViewModel extends Observable {
    private _appVersion : string;

    constructor() {
        super();

        appVersion.getVersionName().then((result) => {
            this._appVersion = result;
            this.notifyPropertyChange("appVersion", this._appVersion);
        });
    }

    get appVersion() : string {
        return this._appVersion;
    }

    public logout() {
        firebase.logout().then((result) => {
            Navigator.navigateTo({
                moduleName : "views/register/register",
                backstackVisible : false,
                clearHistory : true
            })
        }).catch((error) => {
            dialogs.alert({
                title: "Error",
                message: "A system error occurred trying to logout.",
                okButtonText: "Ok"
            });
        });
    }
}