2016-10-24 102 views
0

app.component這樣的:路由器+變化而變化[Angularjs 2]

import { Component, Input } from '@angular/core'; 

import {AuthTokenService} from './auth-token.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    constructor(
     private Auth: AuthTokenService) { }; 

    isGuest: any = this.Auth.canActivate(); 
    title = 'app works!'; 
} 

,我需要從子組件改變isGuest VAR login.component

app.component.html我有這樣的:

<h1> 
    {{isGuest}} 
</h1> 
<router-outlet></router-outlet> 

我試着用@Output and Emitter改變它,但它不工作,因爲我是我們成角度路由器。

+0

'isGuest:任何= this.Auth.canActivate();'這是不正確的行。除此之外,您可以使用服務從childcmp對parentcmp進行更改。 – micronyks

+0

爲什麼這是不正確的?你應該怎麼樣才能向我展示一個例子? –

+0

'constructor( private Auth:AuthTokenService){this.isGuest = Auth.canActivate();}'OR'ngOnInit(){ this.isGuest = this.Auth.canActivate();}' – micronyks

回答

0

我會去更新auth服務來提供Angular文檔中的Observable(https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service)。

import { Injectable } from '@angular/core'; 
import { Subject } from 'rxjs/Subject'; 
@Injectable() 
export class AuthService { 
    /* ... */ 
    private canActivateSource = new Subject<string>(); 
    public canActivate$ = this.canActivateSource.asObservable(); 
    /* ... */ 
    authenticate() { 
    /* ... */ 
    if (authenticated) { 
     this.canActivateSource.next(true); 
    } else { 
     this.canActivateSource.next(false); 
    } 
    /* ... */ 
    } 
    /* ... */ 
} 

然後你就可以在你的app.component訂閱像這樣:

this.Auth.canActivate$.subscribe(canActivate => { 
    /* do something with canActivate */ 
}); 

而且從你的模板,使用async管:

{{ Auth.canActivate$ | async }} 

https://angular.io/docs/ts/latest/api/common/index/AsyncPipe-pipe.html