2016-10-11 9 views
0

ユーザー情報オブジェクトをすべての低レベルコンポーネントに渡そうとしています。 孫の場合でも恋人のコンポーネントに渡す最善の方法は何ですか? @ inputが動作するか、それを他の方法で渡す場合は?他のコンポーネントにデータを渡す最も良い方法は何ですか

ルートコンポーネントのための私のコードは次のとおりです。

constructor(private _state: GlobalState, 
       private _imageLoader: BaImageLoaderService, 
       private _spinner: BaThemeSpinner, public af: AngularFire) { 

    this._loadImages(); 

    this._state.subscribe('menu.isCollapsed', (isCollapsed) => { 
     this.isMenuCollapsed = isCollapsed; 
    }); 

    // this.af.auth.subscribe(
    // user => this._changeState(user), 

    this.af.auth.subscribe(user => this._changeState(user)); 

    } 
+2

どのような性質に関して最良の方法ですか? – Alex

+0

https://angular.io/docs/ts/latest/cookbook/component-communication.html –

答えて

3

は、サービスクラスを作成すると考えたことがありますか?彼らはシングルトンなので、そのクラスの同じインスタンスが、それを求めるすべてのコンポーネントに注入されます。

https://angular.io/docs/ts/latest/guide/dependency-injection.html

簡単なものは、この

import { Injectable } from '@angular/core'; 

@Injectable() 
export class DummyService { 
    public userInfo: UserInfo = { 
     //User stuff goes here 
    }; 
} 

のようになります。そして、あなたは、このようなコンポーネントに追加します。

import {DummyService} from 'dummy.service'; 

@Component({ 
    selector: 'my-component', 
    templateUrl: 'my.component.html' 
}) 
export class MyComponent{ 
    constructor(private myDummyService: DummyService){} 
} 

実行時に、これは、クラスの同じインスタンスを注入するすべてのコンポーネントに注入します。それは、複数のコンポーネント間でデータを同期させる非常に便利な方法です。

+1

彼らはシングルトンではありません。それらは「モジュールスコープ」です。あなたがそれをアプリケーションルートモジュールで提供している限り、Angularはすべての子コンポーネントに同じサービスインスタンスを注入します。しかし、角度スタイルガイドのようなフィーチャモジュールごとに特別な注意が必要です。 –

関連する問題