gpt4 book ai didi

angular - 使用 observable in angular 观察一个变量

转载 作者:行者123 更新时间:2023-12-05 02:16:55 24 4
gpt4 key购买 nike

我有一个名为 loading 的变量(开始时它是 false,它是一个 bool 变量)和一个按钮,其文本取决于该变量。

我写了一个方法来像这样为我做这件事:

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 并在构造函数中订阅可观察对象...然后添加一个简单的函数来发出带有 next 的更改...像这样:

  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);
}

检查 working example in stakblitz

关于angular - 使用 observable in angular 观察一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com