親コンポーネントのアプローチ (属性を介してデータを渡す) は完全に有効でありながら優れた実装ですが、ストアファクトリを使用して同じことをより簡単な方法で実現できます。
基本的に、データは によって保持され、Store
両方のコンポーネント スコープで参照され、状態が変化したときに UI をリアクティブに更新できます。
例:
angular
.module('YourApp')
// declare the "Store" or whatever name that make sense
// for you to call it (Model, State, etc.)
.factory('Store', () => {
// hold a local copy of the state, setting its defaults
const state = {
data: {
heroes: [],
viewType: 'grid'
}
};
// expose basic getter and setter methods
return {
get() {
return state.data;
},
set(data) {
Object.assign(state.data, data);
},
};
});
次に、コンポーネントには次のようなものが必要です。
angular
.module('YourApp')
.component('headerComponent', {
// inject the Store dependency
controller(Store) {
// get the store reference and bind it to the scope:
// now, every change made to the store data will
// automatically update your component UI
this.state = Store.get();
// ... your code
},
template: `
<div ng-show="$ctrl.state.viewType === 'grid'">...</div>
<div ng-show="$ctrl.state.viewType === 'row'">...</div>
...
`
})
.component('mainComponent', {
// same here, we need to inject the Store
controller(Store) {
// callback for the switch view button
this.switchViewType = (type) => {
// change the Store data:
// no need to notify or anything
Store.set({ viewType: type });
};
// ... your code
},
template: `
<button ng-click="$ctrl.switchViewType('grid')">Switch to grid</button>
<button ng-click="$ctrl.switchViewType('row')">Switch to row</button>
...
`
実際の例を見たい場合は、この CodePen をチェックしてください。
そうすることで、2 つまたは N 個のコンポーネント間の通信を有効にすることもできます。次のことだけを行う必要があります。
- ストアの依存関係を注入する
- ストア データをコンポーネント スコープにリンクしていることを確認してください
上記の例のように ( <header-component>
)。
現実の世界では、典型的なアプリケーションは大量のデータを管理する必要があるため、何らかの方法でデータ ドメインを論理的に分割する方が理にかなっています。同じアプローチに従って、さらに Store ファクトリを追加できます。たとえば、現在ログに記録されているユーザー情報と外部リソース (カタログなど) を管理するには、UserStore
プラス a CatalogStore
-- またはUserModel
and CatalogModel
;を作成できます。これらのエンティティは、バックエンドとの通信、カスタム ビジネス ロジックの追加などを一元化するのにも適しています。その場合、データ管理はStore
工場の単独の責任となります。
ストア データを変更していることに注意してください。このアプローチは非常にシンプルで明確ですが、副作用が発生するため、うまく拡張できない可能性があります。より高度なもの (不変性、純粋関数、単一状態ツリーなど)が必要な場合は、 Reduxを確認してください。最終的に Angular 2 に切り替えたい場合は、ngrx/storeをご覧ください。
お役に立てれば!:)
場合によっては移行する場合に備えて、Angular 2 の方法で行う必要はありません
...それを行うことが理にかなっている場合は、それを行います。