[英]load app component data in angular 2 after login user on other page
我有app.component在頂部有一個菜單。 當用戶登錄到登錄頁面時,它會重定向到數據頁面列表,並且用戶應該在頂部菜單中看到他的電子郵件,但不會在app.component中的ngonit上加載。 當我重新加載頁面時,它會出現在這里。
用戶登錄並重定向到數據列表頁面后,我需要它正確。
app.component:
export class AppComponent implements OnInit{
title = 'app works!';
userEmail: any;
constructor(private authService: AuthService, private router: Router) { }
ngOnInit() {
this.userEmail = this.authService.getUser().name;
console.log(this.userEmail);
}
}
登錄組件:
onLogin(){
const user ={
email: this.email,
password: this.password
}
this.authService.loginUser(user).subscribe((data)=>{
if(data.success){
this.authService.userData(data.token, data.user);
this.flashMessage.show('You are logged in.', {cssClass: 'alert-success'});
this.router.navigate(['/']);
}else{
console.log('user didn\'t logged in');
this.flashMessage.show('You are not logged in. Wrong email or password.', {cssClass: 'alert-danger', timeout: 2000})
this.router.navigate(['/login']);
}
});
}
您需要使用戶在登錄服務中是可觀察的。 然后讓AppComponent訂閱可觀察對象。 然后,一旦成功登錄,就讓登錄方法發送下一個可觀察的值。 AppComponent中的訂閱將被觸發,您的值將在那里。 那有意義嗎?
您可以在Angular文檔中看到一個很好的例子。 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.