[英]Angular2 / Ionic2 / TypeScript “two way” binding not updated if i use as reference in async function
I created a simple class in TypeScript: 我在TypeScript中创建了一个简单的类:
export class LoginInformation {
private _UserName: string;
public get userName(): string {
return this._UserName
}
public set userName(v: string) {
this._UserName = v;
}
}
Then i can instantiate the class: 然后我可以实例化该类:
private _LoginInformation: LoginInformation;
this._LoginInformation = new LoginInformation();
(and also implement the getter and setter), then assign a value (并实现getter和setter),然后分配一个值
this.loginInformation.userName = "User1";
Now I can use the Object in my HTML: 现在,我可以在HTML中使用对象:
<ion-item>
<ion-input type="text" placeholder="Name" [(ngModel)]="loginInformation.userName"></ion-input>
</ion-item>
Now i can change my Object-Property 现在我可以更改我的对象属性
this.loginInformation.userName = "User2";
and the screen is updated in the expected way. 并以预期的方式更新屏幕。 Even if i set:
即使我设置:
var self: LoginInformation = this.loginInformation;
self.userName = "User3";
everything is OK. 一切都好。 But if I use an async function (eg get a value from the app preferences - plugin)
但是,如果我使用异步功能(例如,从应用程序首选项中获取值-插件)
this._AppPreferences.fetch(
(value) => {
self.userName = "User4";
},
(error) => {
alert("Error loading Configuration: " + error);
},
"LoginInformation");
the on-screen value is not updated. 屏幕上的值不会更新。 I thought that the assignment of the reference
我以为参考的分配
self: LoginInformation = this.loginInformation
Should work in the expected way. 应该以预期的方式工作。 But it seems that something is missing.
但是似乎缺少了一些东西。
Any ideas what I'm doing wrong? 有什么想法我做错了吗?
You don't need to use self.userName
, you should be able to use this.userName
since you are in an arrow function: 您不需要使用
self.userName
,因为您使用的是箭头功能,所以应该可以使用this.userName
:
this._AppPreferences.fetch(
(value) => {
this.userName = "User4";
},
(error) => {
alert("Error loading Configuration: " + error);
}
);
Don't instantiate the service by yourself. 不要自己实例化服务。 You might end up having several instances instead of a singleton.
您可能最终会拥有多个实例而不是一个实例。 Use NG2's dependency injection to do that automagically for you!
使用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.