[英]watch a variable using observable in angular
我有一個名為loading
的變量(它在開頭是false
的,它是一個布爾變量)和一個按鈕,它的文本依賴於該變量。
我寫了一個方法來為我這樣做:
changeBtnTxt() {
this.loginBtn = this.loading ? 'please wait':'login';
}
現在,我想知道如何使用RxJS
Observable觀察變量以觸發此方法。
這是我的組成部分
export class LoginFormComponentComponent implements OnInit {
loading = false;
loginBtn = 'ورود';
loginModel: LoginFormModel = new LoginFormModel();
@ViewChild('loginForm') form: any;
constructor(private service: LoginFormService,
private basicView: BasicViewService) {} // inject services to our component
ngOnInit() {}
login() {
this.loading = true;
this.changeBtnTxt(); // I want to remove this line and do the changes just by above code
this.service.loginModel = this.loginModel;
this.service.doLogin() // returns a Http get Observable
.subscribe(
res => {
},
msg => {
if (msg.status !== 401) {
this.loading = false; // want back to normal without call changeBtnTxt()
}
});
this.form.reset();
}
changeBtnTxt() {
this.loginBtn = this.loading ? 'ورود' : 'لطفا صبر کنید';
}
}
這里是它的HTML
<form novalidate #loginForm="ngForm" (submit)="login()">
<div class="ibox-title">
<h2 class="font-bold">ورود به حساب کاربری</h2>
</div>
<div class="ibox-content" style="padding-bottom: 15px;">
<div class="form-group">
<input type="text" class="form-control"
placeholder="نام کاربری"
name="username"
[(ngModel)]="loginModel.username"
required
#username="ngModel">
</div>
<div class="form-group" style="margin-bottom:0px">
<input type="password" class="form-control"
placeholder="رمزعبور"
name="password"
[(ngModel)]="loginModel.password"
required
#password="ngModel">
</div>
</div>
<div class="ibox-footer">
<input type="submit" class="btn btn-primary block full-width m-b"
[disabled]="loginForm.invalid || loading" [value]="loginBtn"/>
<button class="btn btn-sm btn-white btn-block" (click)="showHelp()">راهنما</button>
</div>
</form>
您可以使用Subject並訂閱構造函數中的observable ...然后添加一個簡單的函數來發出下一個更改...像這樣:
public myObservable = new Subject<boolean>();
constructor() {
this.myObservable.subscribe(val => {
this.loading = val;
this.loginBtn = 'loged in';
alert(this.loading)
})
}
changeBtnTxt() {
this.loginBtn = 'please wait';
setTimeout(() => { // Only for demonstration purpose
const val = (this.loading == true ? false : true);
this.myObservable.next(val);
}, 2000);
}
這是一個想法,你可以使用getter和setter方法,而不必使用observable:
private _loading: boolean = false;
public get loading(): boolean {
return this._loading;
}
public set loading(isLoading: boolean) {
this._loading = isLoading;
this.changeBtnTxt();
}
然后你只需像正常變量一樣使用loading
:
this.loading = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.