使用角度

时间:2018-02-16 00:14:11

标签: angular angular5

我有一个名为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>

2 个答案:

答案 0 :(得分:2)

你可以使用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);
  }

检查working example in stakblitz

答案 1 :(得分:1)

这是一个想法,你可以使用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;