订阅app.component构造函数中的BeahviorSubject仅在第一次应用程序加载时触发

时间:2017-09-14 00:32:31

标签: angular rxjs observable ionic3 behaviorsubject

在Ionic 3项目中使用Angular2:

我需要根据用户订阅计划更改app.component中的菜单。为了在登录后执行此操作,我有一个BehaviorSubject的currentUser $ asObservable。这是我的代码设置:

app.component.ts - >构造:

    this._authProvider.currentUser$
  .subscribe(currentUser => {
    //this._accountsAndSettings = accountsAndSettings
    triggered++;
    console.log('triggered', triggered);
    if (currentUser.license === "Agency") {
      this._isAgency = true;
    };
    this
      ._menuController
      .enable(true);
    this._rootPage = "MainTabsPage";
  }, accountsAndSettingsError => {
    //Display AlertController and call platform.ready()
    this._rootPage = "AuthLoginPage";
  });

loginPage.ts - >登录:

  private _login(): void {
//Check for missing credentials
if (this._loginForm.invalid) {
  //Alert pop-up
  let missingCredentialsAlert = this
    ._alertController
    .create({
      message: "Some credentials are missing",
      buttons: [
        {
          text: "Ok",
          role: 'cancel'
        }
      ]
    });
  missingCredentialsAlert.present();
  //Call login
} else {
  let loginLoading = this
    ._loadingController
    .create({ content: "Logging you in ..." });
  loginLoading.present();
  let loginRequestBody = {
    email: this._loginForm.value.email,
    password: this._loginForm.value.password
  }
  this
    .authProvider
    .login(loginRequestBody)
    .subscribe(currentUser => {
      loginLoading.dismiss();          
    }, currentUser => {
      loginLoading.dismiss();
      let alert = this
        ._alertController
        .create({
          title: null,
          message: currentUser.msg_id,
          buttons: [
            {
              text: "Ok"
            }
          ]
        });
      alert.present();
    });
};

authProvider - >构造:

  private _currentUserSource: BehaviorSubject<userInfo> = new BehaviorSubject(null);
  public updatedCurrentUser$ = this
    ._currentUserSource
    .asObservable();

authProvider - &gt;登录:

  public login(loginRequestBody): Observable<object> {
return this
  ._http
  .post('/user/login', loginRequestBody)
  .flatMap(response => {
    return Observable.fromPromise(this._ionicStorage.set(this._keyForUserInfoInStorage, response.json().userAndSettings).then(savedUserInfo => {
      this
        ._currentUserSource
        .next(savedUserInfo);
      return savedUserInfo;
    }));
  })
  .catch(loginError => {
    return Observable.throw(loginError);
  });
  }; end login

登录代理商用户后,我希望该页面可以通过代理商菜单更改为MainTabsPage(_isAgency用于* ngIf以显示其他菜单项)。 发生的事情是登录后页面仍然登录,并且app.component构造函数中不会触发订阅。

0 个答案:

没有答案