繁体   English   中英

如果我在异步函数中用作引用,则不会更新Angular2 / Ionic2 / TypeScript“双向”绑定

[英]Angular2 / Ionic2 / TypeScript “two way” binding not updated if i use as reference in async function

我在TypeScript中创建了一个简单的类:

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";

一切都好。 但是,如果我使用异步功能(例如,从应用程序首选项中获取值-插件)

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

屏幕上的值不会更新。 我以为参考的分配

self: LoginInformation = this.loginInformation

应该以预期的方式工作。 但是似乎缺少了一些东西。

有什么想法我做错了吗?

您不需要使用self.userName ,因为您使用的是箭头功能,所以应该可以使用this.userName

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

不要自己实例化服务。 您可能最终会拥有多个实例而不是一个实例。 使用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){

   }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM