Angular 2检查子组件是否准备就绪

时间:2016-09-18 10:05:58

标签: angular

是否可以在根组件AppComponent中检查其子组件是否已准备就绪。子组件是使用AppComponent模板中的路由和<router-outlet>指令加载的组件。子组件路由具有异步身份验证保护canActivate。我想在身份验证后卫完成时在AppComponent中执行一些代码。

3 个答案:

答案 0 :(得分:0)

请参阅component communication,例如 Parent侦听子事件

答案 1 :(得分:0)

使用服务。在AppComponent NgModule的angular.element(document.getElementById('yourElementId')).scope(); 中注册服务(或直接在AppComponent上注册)。该服务可以具有AppComponent所订阅的EventEmitter或Subject。身份验证后卫完成后,它会在服务上发出一个事件,

答案 2 :(得分:0)

查看我的UserService。

import { Injectable, ApplicationRef } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Router, ActivatedRoute } from '@angular/router';

@Injectable()
export class UserService
{
  id: number;
  userEmail: string;
  userName: string;
  gravatar:
  {
    md5: string
    ,defaultAva: string
  };

  loggedIn = false;
  private initUser: Promise<void>;

  constructor
  (
    private http: Http
    ,private router: Router
    ,private route: ActivatedRoute
    ,private applicationRef: ApplicationRef
  )
  {
    this.initUser = this.login();
  }

  login()
  {
    return this.http
    .get('/api/session')
    .toPromise()
    .then( session =>
    {
      let user: UserService = session.json();

      this.setUser(user);
    })
    .catch( err =>
    {
      console.log( err );
    });
  }

  setUser(user: UserService)
  {
    if( user && user.id )
    {
      this.loggedIn = true;

      for( let prop in user )
      {
        this[prop] = user[prop];
      }

      this.gravatar.defaultAva = 'https://www.gravatar.com/avatar/00000000000000000000000000000000';

      // App-notification event "user is loggedIn"
      this.applicationRef.tick();
    }
  }

  redirectIfNoLoggedIn()
  {
    return this.initUser
    .then( () =>
    {
      if( !this.loggedIn )
      {
        this.router.navigate( ['pre-account/login'] );
      }
    })
    .catch( err =>
    {
      console.log(err);
    })
  }

  logout()
  {
    this.http
    .delete('/api/session')
    .toPromise()
    .then( session =>
    {
      if( session && session.json().ok )
      {
        this.id = null;
        this.userEmail = null;
        this.userName = null;

        this.loggedIn = false;
      }

      // App-notification event "user is loggedOut"
      this.applicationRef.tick();
    })
    .catch( err =>
    {
      console.log( err.json() );
    });
  }
}

现在我可以按如下方式使用此服务:

export class AccountModule
{
  constructor( private user: UserService)
  {
    user.redirectIfNoLoggedIn();
  }
}