[英]Best practice for getting an immutable item to edit in a component from an RXJS/NGRX store in Angular
[英]Angular 2 ngrx/store best practice
在我的angular 2應用程序中,我開始將所有項目重構為ngrx模式,但是我仍然有一些疑問:
我要檢索什么應用程序列表和應用程序類別列表
1-在這種情況下,我可以用舊方法來管理類似“ selectedCategory”(只能選擇一個這樣的狀態,以其為原語)的狀態嗎? :
Categories.component.ts
...
...
OnCategorySelect (applicationID : string) {
this.selectedCategory = applicationID
}
還是應該為此創建一個selectedCategory減速器?
2-將數據從智能組件(applicationsListComponent)傳遞給啞巴(categoryComponent)時,我使用異步管道以這種方式進行操作:
**ApplicationsListComponent.ts**
....
....
<app-category [categories]='appCategories | async'></app-category>
在這種情況下,我應該將changeDetection: ChangeDetectionStrategy.OnPush
組件中的changeDetection: ChangeDetectionStrategy.OnPush
放入嗎?
3-在我的笨組件(categoryComponent)中,當我從@Input接收到智能組件中的categories
時,我沒有將其聲明為Observable,但是我正在這樣做:
category.component.ts
@Input() appCategories: CategoryInfo[];
category.component.html
<div *ngFor='let app of appCategories'>....</div>
因此,在這種情況下,我不知道我是否必須將@Input從智能組件接收的數據聲明為Observable。
有什么建議么 ?
1-對於這種情況,我創建了單獨的減速器“ selectedCategory”。 它的實現非常簡單
import { ActionReducer, Action } from '@ngrx/store';
import { SELECT_CATEGORY } from '../actions';
export const selectedCategory: ActionReducer<ICategory> = (state: ICategory, {type, payload}: Action) => {
switch (type) {
case SELECT_CATEGORY:
return payload;
default:
return state;
}
};
2-是的 在ngrx中存儲是不可變的。 這意味着Angular沒有必要監視某些對象的屬性是否已更改。 輸入數據可以更改的唯一方法是更改整個@Input
對象。 所以changeDetection: ChangeDetectionStrategy.OnPush
很好。
3-否。 @Input
屬性不應為Observable。 通過async
管道(如您的示例)將它們綁定就足夠了。 如果直接將Observable傳遞給轉儲組件(沒有async
),則Angular更改檢測將無法按預期工作。 即使實際數據會更改,對Observable
對象的引用也將始終保持不變。 在這種情況下,如果您想對數據更改做出反應,則需要手動訂閱(取消訂閱) Observable
,這將變得一團糟。
要添加更多@ user1614543的答案
如果您想檢測@Input上的更改,該更改來自可觀察的來源。
在您的啞組件中使用以下代碼。
ngOnChanges(changes: SimpleChanges) {
if (changes.hasOwnProperty('appCategories')) {
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.