【问题标题】:Angular 2 ngrx/store best practiceAngular 2 ngrx/store 最佳实践
【发布时间】:2016-12-08 15:55:55
【问题描述】:

在我的 angular 2 应用程序中,我开始将所有项目重构为 ngrx 模式,但我仍然有一些问题:

我的应用程序如何检索应用列表和应用类别列表

1- 在这种情况下,我可以用旧方式管理像“selectedCategory”这样的状态吗(只能选择一个,所以它只是一个原语)? :

Categories.component.ts

...
...
OnCategorySelect (applicationID : string) {
this.selectedCategory = applicationID 
}

或者我应该为此创建一个 selectedCategory reducer 吗?

2 - 当将数据从智能组件(applicationsListComponent)传递到哑组件(categoryComponent)时,我使用异步管道这样做:

**ApplicationsListComponent.ts**

....
....
<app-category [categories]='appCategories | async'></app-category>

在这种情况下,我应该将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。

有什么建议吗?

【问题讨论】:

    标签: angular redux ngrx


    【解决方案1】:

    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 属性不应该是 Observables。通过async 管道(如您的示例)绑定它们就足够了。如果您将 Observable 直接传递给转储组件(没有 async),那么 Angular 更改检测将无法按预期工作。对Observable 对象的引用将始终保持不变,即使实际数据会发生变化。在这种情况下,如果您想对数据更改做出反应,您需要手动订阅(和取消订阅)Observable,这将变得一团糟。

    【讨论】:

      【解决方案2】:

      在@user1614543 的回答中添加更多内容

      如果您想检测来自可观察来源的@Input 的变化。

      在您的哑组件中使用以下代码。

      ngOnChanges(changes: SimpleChanges) { 
        if (changes.hasOwnProperty('appCategories')) {
           ...
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-26
        • 1970-01-01
        • 2018-12-06
        • 2018-03-15
        • 2018-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多