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

Angular.io / Angular 4. How do I refresh one component view when triggering another

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

我有一个呈现用户名的 NavbarComponent。

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

这就是问题所在。我的导航栏不显示用户名。但是如果我做一个 refresh/ctrl+r 用户名被呈现。

怎么了?

app.component.html

<nav-bar></nav-bar>
<router-outlet></router-outlet>

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

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

由于组件已经初始化,登录后 ngOnInit() 不会 运行。针对您的情况的一种解决方案是订阅一个路由器参数来检查用户是否已登录。

例如

this.route.queryParams
        .map(params => params['loggedIn'])
        .subscribe(loggedIn => {
            if (loggedIn) {
                this.me = JSON.parse(localStorage.getItem('currentUser'));
            }
        });

如 JusMalcolm 所述,OnInit 不再 运行。

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

在您的 NavBarComponent 中导入 Subject 并声明它:

import { Subject } from 'rxjs/Subject';

....

public static updateUserStatus: Subject<boolean> = new Subject();

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

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

然后在您的 LoginComponent 中导入您的 NavbarComponent,当您成功登录后,只需在主题上调用 next()NavbarComponent 就会订阅它.

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

您也可以使用共享服务告诉 NavbarComponent 重新执行用户检索。有关来自 Official Docs.

的共享服务的更多信息

如果您可以在身份验证时 return 来自后端的名称,您可以将 AuthenticationService 注入 NavbarComponent 并在 navbar.component.html 中绑定所需的名称。

导航栏组件:

export class NavbarComponent {
   ...
   constructor(private authservice: AuthenticationService) {}
   ...
}

navbar.component.html:

<span>Welcome {{authservice.name}}!</span>