2017-08-17 6 views
0

問題を1行で記述するのは難しいですが、より詳細な説明があります:別のコンポーネントに置き換えられ、角2で戻されるコンポーネント間でデータを渡す方法は?

いくつかのフィルタでロケットをフィルタリングし、Fと呼ぶ画面があるとします。 anything - ラジオボタン、入力フィールドなど。フィルタの設定に応じて、いくつかのデータをグリッドに表示する「表示」ボタンがあります。フィルターの中

、「選択モデル」ボタンがあります。

あなたはこの選択モデル]ボタンをクリックすると、それはあなたがrocketshipモデルを決定することができます大きな機能のように、あなたはフィールドの別のセットを持っている別の画面に表示されます。 「OK」と表示されているボタンをクリックすると、最初の機能に戻り、選択したものに関するデータをロケットモデルとして送信する必要があります。

がこれに別のレベルがあって、あなたがrocketshipのモデルを選択したところ、あなたはrocketshipのidontknowwhatを選択するために、別の機能に移動しなければならない場合はどうすれば?あなたは角度でこの機能を実装するに行くかどう

?ルータ、ポップアップなどを使用する必要がありますか?

+0

が重複する可能性:// stackoverflow.com// 45668262/2708210' –

答えて

1

別のコンポーネントで置き換えられるコンポーネント間でデータを渡すと、複数のコンポーネントによって読み取られ、変更される可能性のあるデータがあるとします。これを実現するために、あなたはangular servicedependency injectionbehavior subject、およびsubscriptionの助けを借りて、routerを使用することができます。

まず、データとしてbehaviorSubjectプロパティでangular serviceを作成します。

@Injectable() 
export class DataService() 
{ 
    public data: Subject<any> = new BehaviorSubject<any>(null); 

    changeData(newData: any) { 
    this.data.next(newData); // this will update the value of the `data` with `newData`, and any component which subscribe to `data` will get the updated value of `data`. 
    } 
} 

注射用サービスは、ユーザーが他のコンポーネントからコンポーネントへとジャンプしながらデータを保持することができます。次のステップは、データを必要とするコンポーネントにこのサービスを注入することです。のは、例えばデータが必要ComponentAComponentBを見てみましょう:

@Component({ 
    selector: 'component-a' 
    providers: [DataService], 
    templateUrl: `component-a.html` 
)} 

export class ComponentA { 
    constructor(private dataService: DataService) { 
    this.dataService.data.subscribe((value) => { 
     // here, component A able to always get the updated value of the data when its value is changed. 
    }); 
    } 
} 

そしてComponentBため、のこのコンポーネントは、交換する能力(または更新)データを持っているとしましょう:

@Component({ 
    selector: 'component-b' 
    providers: [DataService], 
    templateUrl: `component-b.html` 
)} 

export class ComponentB { 
    constructor(private dataService: DataService) { 
    this.dataService.data.subscribe((value) => { 
     // here, component B able to always get the updated value of the data when its value is changed. 
    }); 
    } 

    changeData(newData: any) { 
    this.dataService.changeData(newData); // this call will update the value of the data which DataService keeps, therefore when user jump to ComponentA, ComponentA will retrieve the updated value from `this.dataService.data`'s subscription 
    } 
} 

、あなたが使用している場合ルータはこれらの2つのコンポーネントをルーティングし、ユーザが1つのコンポーネントにナビゲートするたびに、そのコンポーネントはデータの最新の値を取得します。 `HTTPSの

+0

おかげであなたの答えのためにたくさん! –

関連する問題