Angular.io / Angular 4.如何在触发另一个

时间:2017-05-03 14:30:54

标签: angular angular2-routing

我有一个简单的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);
                });
    }
}

3 个答案:

答案 0 :(得分:6)

如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即可订阅。< / p>

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

此外,您可以使用共享服务告诉NavbarComponent重新执行用户检索。有关Official Docs的共享服务的更多信息。

答案 1 :(得分:0)

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

例如

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

答案 2 :(得分:0)

如果您可以在进行身份验证时从后端返回名称,则可以将AuthenticationService注入NavbarComponent并在navbar.component.html中绑定所需的名称。

NavbarComponent:

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

navbar.component.html:

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