Angular.io / Angular 4.如何在触发另一个组件视图时刷新它
我有一个简单的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> 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); }); } } 解决方法
正如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,当您成功登录后,只需调用Subject上的next(),NavbarComponent将订阅它. .subscribe( data => { NavbarComponent.updateUserStatus.next(true); // here! this.router.navigate([this.returnUrl]); },// more code here 您还可以使用共享服务来告知NavbarComponent重新执行用户的检索.有关Official Docs的共享服务的更多信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |