路由器+将变量从子组件改为父组件[Angularjs 2]

Router + change variable from child to parent component [Angularjs 2]

本文关键字:组件 Angularjs 变量 路由器      更新时间:2023-09-26

我有这样的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!';
}

我需要从子组件login.component中更改isGuest var

app.component.html中我有这样的:

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

我试图改变它与@Output and Emitter,但它不工作,因为我使用角路由器

我会更新auth服务,像Angular文档(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