简体   繁体   English

在其他页面上登录用户后,以角度2加载应用程序组件数据

[英]load app component data in angular 2 after login user on other page

I have app.component which has a menu on the top. 我有app.component在顶部有一个菜单。 When user logged in in the login page it is redirected to the list of data page and user should see his email in the top menu but it won't loaded on ngonit in app.component. 当用户登录到登录页面时,它会重定向到数据页面列表,并且用户应该在顶部菜单中看到他的电子邮件,但不会在app.component中的ngonit上加载。 When I reload the page it is appear there. 当我重新加载页面时,它会出现在这里。

I need it to be right after user logged in and redirected to the data list page. 用户登录并重定向到数据列表页面后,我需要它正确。

app.component: 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);
  }
}

login component: 登录组件:

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']);
      }
    });

  }

You need to have the user be an observable in the login service. 您需要使用户在登录服务中是可观察的。 And then have the AppComponent subscribe to the observable. 然后让AppComponent订阅可观察对象。 Then once you login successfully, have the login method send the next observable value. 然后,一旦成功登录,就让登录方法发送下一个可观察的值。 The subscription in the AppComponent will be triggered and your value will be there. AppComponent中的订阅将被触发,您的值将在那里。 Does that make sense? 那有意义吗?

You can see a good example in the Angular docs. 您可以在Angular文档中看到一个很好的例子。 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM