我有app.component
这样:
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
login.component
var
在app.component.html
我喜欢这个:
<h1>
{{isGuest}}
</h1>
<router-outlet></router-outlet>
我尝试用@Output and Emitter
更改它,但它无效,因为我使用的是角度路由器。
答案 0 :(得分: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