Using Angular2 in an Ionic 3 project:
I need to change my menu in my app.component based on the user subscription plan. In order to do this after login, I have currentUser$ asObservable of a BehaviorSubject. This is my code setup:
app.component.ts -> constructor:
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 - >login:
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 -> constructor:
private _currentUserSource: BehaviorSubject<userInfo> = new BehaviorSubject(null);
public updatedCurrentUser$ = this
._currentUserSource
.asObservable();
authProvider -> login:
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
After logging in an Agency user, I expect the page to change to MainTabsPage with an Agency menu (_isAgency is used in an *ngIf to show additional menu items). What is happening is that after login the page remains on login, and subscribe is not triggered in app.component constructor.