2016-10-24 15 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!'; 
} 

をそして私は、私はこのようにしていapp.component.htmlで子コンポーネントからlogin.component

isGuest VARを変更する必要があります:

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

私は@Output and Emitterと変更しようとしましたが、私は私たちのために動作しません角度ルータ。

+0

'isGuest:asyncパイプを使用して、

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

そして、あなたのテンプレートからthis.Auth.canActivate(); 'これは不正な行です。それとは別に、サービスを使用してchildcmpからparentcmpに変更を加えることができます。 – micronyks

+0

これはなぜ間違っていますか?どのようにして私に例を示すことができますか? –

+0

'コンストラクタ( 私のAuth:AuthTokenService){this.isGuest = this.Auth.canActivate();}' – micronyks

答えて

0

私はAngularドキュメント(https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service)のようなObservableを提供するためにauthサービスを更新するつもりです。

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で購読することができます=いずれかの:

{{ Auth.canActivate$ | async }} 

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