路由器+从子组件到父组件的变量变量[Angularjs 2]

时间:2016-10-24 17:12:44

标签: javascript angular typescript

我有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更改它,但它无效,因为我使用的是角度路由器。

1 个答案:

答案 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