Angular.io/Angular 4.如何在触发另一个组件视图时刷新它

Chr*_*rks 5 angular2-routing angular

我有一个简单的Angular.io应用程序.(angular-cli/4.1.0)

我有一个NavbarComponent,用于呈现用户名.

第一次访问应用程序时我没有登录,我的应用程序重定向到LoginComponent.我的NavBar也被渲染但没有用户名.成功登录后,我被重定向到我的HomeComponent.

这就是问题所在.我的NavBar不显示用户名.但是,如果我执行刷新/ ctrl + r,则会呈现用户名.

怎么了?

app.component.html

<nav-bar></nav-bar>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

navbar.compoment.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'nav-bar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  me;

  ngOnInit() {
    this.me = JSON.parse(localStorage.getItem('currentUser'));
  }
}
Run Code Online (Sandbox Code Playgroud)

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, AuthenticationService } from '../_services/index';

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService,
        private alertService: AlertService) { }

    ngOnInit() {
        // reset login status
        this.authenticationService.logout();

        // get return url from route parameters or default to '/'
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.email, this.model.password)
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                    this.errorMsg = 'Bad username or password';console.error('An error occurred', error);
                });
    }
}
Run Code Online (Sandbox Code Playgroud)

AJT*_*T82 6

如JusMalcolm所述,OnInit不会再次运行.

但您可以使用a Subject来告诉NavbarComponent从本地存储中获取数据.

NavBarComponent导入Subject并声明它:

import { Subject } from 'rxjs/Subject';

....

public static updateUserStatus: Subject<boolean> = new Subject();
Run Code Online (Sandbox Code Playgroud)

然后在你的构造函数中订阅:

constructor(...) {
   NavbarComponent.updateUserStatus.subscribe(res => {
     this.me = JSON.parse(localStorage.getItem('currentUser'));
   })
}
Run Code Online (Sandbox Code Playgroud)

在您的LoginComponent导入中NavbarComponent,当您成功登录时,只需调用next()主题,并NavbarComponent订阅它.

.subscribe(
   data => {
      NavbarComponent.updateUserStatus.next(true); // here!
      this.router.navigate([this.returnUrl]);
   },
   // more code here
Run Code Online (Sandbox Code Playgroud)

您还可以使用共享服务来指示NavbarComponent重新执行用户的检索.有关官方文档的共享服务的更多信息.