2016-12-19 67 views
1

我需要在登錄後編輯組件的某些屬性。例如我需要編輯HomeComponent的消息屬性和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'); 
    } 
} 
+0

我完全不明白你的問題。 'HomeComponent'和'UserComponent'如果你懷疑這種情況下最好的解決方案是什麼,那麼使用服務。另見https://angular.io/docs/ts/latest/cookbook/component-communication.html – yurzui

回答

3

使用與觀測共享服務和訂閱的變化:

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'); 
    } 
} 
+0

我在'rxjs/Rx'中添加了「import {BehaviorSubject,Observable};」在頂部行[ts]屬性'toObservable'在類型'BehaviorSubject '上不存在。你有什麼想法如何解決這個問題? – TyForHelpDude

+1

對不起,應該是'asObservable()'參見https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service –

相關問題