![](/img/trans.png)
[英]Loading a sidemenu into a DOM with Ionic2 and Angular2 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.