问题
i am using mongoDB as my backed,
firebase.auth().onAuthStateChanges() method listens when authentication state changes in our app. thats really Cool.
But same thing not happened in my case because of not similar backed i used.
i will share my code in below before that i will tell you what i trying to get the user via constructor in app.component.ts. when the user successfully Logged in to my app i am getting user with unique token which i am storing in ionicStorage. at the same time i had called a service in the constructor of app.component.ts to get the user from my localstorage. it is working But my app.component is not triggering when user signs up ? i need to manually reload the page once then out root component triggered , service called , getting data of user showing in the sidemenu?
i dont want to reload my page to show the user.
//app.component.ts
export class MyApp {
constructor(getDataService:GetDataService
,public storage: Storage) {
this.storage.get('user').then(userResp => {
this.user = userResp;
console.log('signup user : ' + JSON.stringify(userResp));
});
})}
//app.html
<ion-content>
<div *ngIf="user" padding>
Hi {{user.displayName}}
</div></ion-content>
thanks,
回答1:
But my app.component is not triggering when user signs up? Do I need to manually reload the page once then out root component triggered, service called, getting data of user showing in the sidemenu?
Yes, you need to tell the app component that the data has changed. But you can use events to do so. So in your auth service, you can publish some events when the user signs in or out:
import { Events } from 'ionic-angular';
// ...
@Injectable()
export class AccountService {
constructor(..., public events: Events) {}
public login(): any {
// your logic...
// Publish the `user:login` event, sending true
this.events.publish('user:login', true);
}
public logout(): any {
// your logic...
// Publish the `user:login` event, sending false
this.events.publish('user:login', false);
}
}
And then in your app.component file, subscribe to those events to handle each scenario:
export class MyApp {
constructor(getDataService: GetDataService, public storage: Storage, public events: Events) {
this.storage.get('user').then(userResp => {
this.user = userResp;
console.log('signup user : ' + JSON.stringify(userResp));
});
events.subscribe('user:login', (loggedIn) => {
if(loggedIn) {
// Get the user details again
this.storage.get('user').then(userResp => {
this.user = userResp;
console.log('signup user : ' + JSON.stringify(userResp));
});
} else {
// Reset the user details shown in the side menu
this.user = null;
}
});
}
}
来源:https://stackoverflow.com/questions/44214109/ionic2-how-to-manage-user-state-in-our-app-in-sidemenu