2017-06-20 5 views
-2

後angular2でHTMLページ内のデータのオブジェクトが、直面する問題をバインドするためにはどのように結合するために、このメソッドを使用しますが、私はページをリロードしたときにその作業は、次のようなものを見ることができるはリロード

<div><h1>{{userdata?.firstname}}</h1></div> 

export class HomeComponent { 

    constructor(private authenticationService : AuthenticationService) { 
     userdata=this.authenticationService.user_data; 
    } 
} 
+0

?あなたのコードを投稿できます –

+1

多くのコードがありません。まず第一に、コンポーネントがありますか? – trichetriche

+0

前の質問で説明したように、コンストラクタに割り当てた後に、ユーザデータをログに記録してみてください。すべての '?'(elvis演算子)は、オブジェクトが存在することを確認してから、サブオブジェクトを探します。あなたのオブジェクトに何が入っているかを見ることが重要です。正しいフィールドがないかもしれません。あるいは、あなたの 'authenticationService'が何も返さないかもしれません。 – MichaelSolati

答えて

1

あなたのサービスを停止します。..実際にあなたの関心事である何。

import { Injectable } from '@angular/core'; 
import { BehaviorSubject, Observable } from 'rxjs'; 

@Injectable() 
export class AuthenticationService { 
    private _user_data: BehaviorSubject<any> = new BehaviorSubject<any>(null); 

    constructor() { 
    this._restoreUser() 
    } 

    get user_data(): Observable<any> { 
    return this._user_data.asObservable(); 
    } 

    private _restoreUser(): void { 
    let user: any; 
    // use any code to restore user from cache and assign it to the scoped user variable 
    this._user_data.next(user); 
    } 
} 

そして、あなたの自宅のコンポーネントで...

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { Subscription } from 'rxjs/Subscription'; 

export class HomeComponent implements OnInit, OnDestroy { 
    public userdata: any; 
    private _userdataSub: Subscription; 

    constructor(private authenticationService: AuthenticationService) { } 

    ngOnInit() { 
    this._userdataSub = this.authenticationService.user_data.subscribe((userdata) => { 
     this.userdata = userdata; 
    }); 
    } 

    ngOnDestroy() { 
    this._userdataSub.unsubscribe(); 
    } 
}