我有两个独立的组件navbar.ts和home.ts。当用户登录时,我将路由到home.ts组件。当我刷新主页时,我无法在home.ts中加载home.ts组件,它正在显示navbar.ts组件。这是密码。
navbar.ts
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Component({
selector: 'navbar',
template: template,
})
export class NavbarComponent implements OnInit {
public isAuthenticated = new BehaviorSubject(false);
constructor(private http: Http, public router: Router,
public loginService: LoginService) {}
ngOnInit() {
if (this.loginService.isLoggedIn()) {
this.isAuthenticated.next(true);
}
}
}
home.ts
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'home',
template: template,
styles: [ styles ],
})
export class Home implements OnInit {
constructor(public router: Router, public http: Http) {}
ngOnInit() {}
}
发布于 2016-11-13 18:48:42
很可能您将您的服务放在ngOnInit中,根据angular2中的生命周期挂钩,它将在加载时只执行一次,因此您希望检查您的服务并检查其更改,尝试ngDoCheck() {}代替,使用此方法检测忽略角度的更改。
DoCheck:当角脏检查指令时调用的生命周期挂钩。
使用方法:
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements DoCheck {
ngDoCheck() {
// ...
}
}
因此,将代码更改为:
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { Component, DoCheck } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Component({
selector: 'navbar',
template: template,
})
export class NavbarComponent implements DoCheck {
public isAuthenticated = new BehaviorSubject(false);
constructor(private http: Http, public router: Router,
public loginService: LoginService) {}
ngDoCheck() {
if (this.loginService.isLoggedIn()) {
this.isAuthenticated.next(true);
}
}
}
希望能帮上忙。
https://stackoverflow.com/questions/40580917
复制相似问题