两个独立组件如何在angular2 js中相互通信?

时间:2016-11-14 02:00:55

标签: angular angular2-routing

我有两个独立的组件navbar.ts和home.ts.我在用户登录时路由到home.ts组件。当我刷新主页时,我无法在home.ts中加载navbar.ts组件它显示了导航栏.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() {}

}

1 个答案:

答案 0 :(得分:0)

你最有可能将你的服务放在ngOnInit中,根据angular2中的生命周期钩子,它只会在加载时执行一次,所以你想检查你的服务并检查它的变化,试试ngDoCheck(){},使用这个检测Angular忽略的变化的方法。

DoCheck:当Angular dirty检查指令时调用的生命周期钩子。

使用方法:

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements DoCheck {
  ngDoCheck() {
    // ...
  }
}

Document is here.

所以请将您的代码更改为:

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);
    }
 }
}
希望它有所帮助。