如何在没有继承的情况下访问组件的属性

时间:2016-12-19 12:47:48

标签: angular typescript

我需要在登录后编辑组件的某些属性。例如,我需要编辑HomeComponent的message属性和UserComponent的age属性,因此继承组件类不是一个选项。我怎样才能实现这个目标

auth.service

// app/auth.service.ts

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

declare var Auth0Lock: any;

@Injectable()
export class Auth {
  lock = new Auth0Lock('asdsd', 'mehmetyeneryilmaz.eu.auth0.com', {});

  constructor() {
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
    });
  }

  public login() {
    this.lock.show();
  }

  public authenticated() {
    return tokenNotExpired();
  }

  public logout() {
    localStorage.removeItem('id_token');
  }
}

1 个答案:

答案 0 :(得分:3)

使用带有observable的共享服务并订阅更改:

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

declare var Auth0Lock: any;

@Injectable()
export class Auth {
  lock = new Auth0Lock('asdsd', 'mehmetyeneryilmaz.eu.auth0.com', {});

  private message = new BehaviorSubject<string>(null);
  public $message = this.message.asObservable(); 

  constructor() {
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
    });
  }

  public login() {
    this.lock.show();
    this.message.next('checking authentication');
  }

  public authenticated() {
    return tokenNotExpired();
  }

  public logout() {
    localStorage.removeItem('id_token');
    this.message.next('successfully logged in');
  }
}
class HomeComponent {
  constructor(auth:Auth) { 
    auth.$message.subscribe(msg => this.message = msg);
  }

}