【问题标题】:Why ngrx return 2 objects even if I add takeUntil and skipWhile?为什么即使我添加了 takeUntil 和 skipWhile,ngrx 也会返回 2 个对象?
【发布时间】:2019-06-13 15:26:07
【问题描述】:

在我的情况下,我的出版物应该只有一个数组列表。但我有 2 个列表,第一个是空的,第二个是我的真实列表。

我没有在我的 html 中使用异步,它只是我从订阅中获取的一个 ngfor。

在我的 ngOnInit 中:

this.publication$ = this.store$.pipe(
    skipWhile(val => val == null),
    select(PublicationFeatureStoreSelectors.selectAllPublicationFeatureItems),
    filter(value => value !== undefined),
);

this.publication$.subscribe(data => {
    takeUntil(this.ngDestroyed$),
        this.piins = data;
    this.publicationAppeared = data.map(a => a._id);
    this.checkIfLiked();
    console.log(data);
});

在我的 ngOnDestroy 中:

this.ngDestroyed$.next();
this.ngDestroyed$.complete();

我的选择器

export const selectAllPublicationsFeatureItems: (
  state: object
) => Publications[] = featureAdapter.getSelectors(selectPublicationsFeatureState).selectAll;

export const selectPublicationsFeatureState: MemoizedSelector<
  object,
  State
> = createFeatureSelector<State>('publicationFeature');

这是我的结果:

[]
(3) [{…}, {…}, {…}]

这是在我的减速器中:

    case ActionTypes.GET_PUBLICATION_SUCCESS: {

       const myobject = featureAdapter.addAll(action.payload, {
        ...state,
        isLoading: false,
        error: null
      });

      console.log(myobject); // the result is just below

      return myobject;
    }

console.log 的结果:

{ids: Array(3), entities: {…}, isLoading: false, error: null}
entities: {5d0261c743d8c30793eb8d25: {…}, 5d01713c7f353a1a81349299: {…}, 5d0170a67f353a1a81349295: {…}}
error: null
ids: (3) ["5d0261c743d8c30793eb8d25", "5d01713c7f353a1a81349299", "5d0170a67f353a1a81349295"]
isLoading: false
__proto__: Object

结果和我在reduxTool上得到的一模一样

如果您有解决方案不要使用并且不要调用第一个数组列表,非常感谢。

我几乎只能使用我的方法 checkIfLiked() 一次

【问题讨论】:

  • 能否请您从subscribe() 中删除takeUntil(this.ngDestroyed$) 并将其移动到filter 操作符之后this.publication$ observable 然后尝试?另外请告诉我们此选择器返回的"PublicationFeatureStoreSelectors.selectAllPublicationFeatureItems" 数据类型。
  • 尝试使用跳过 (learnrxjs.io/operators/filtering/skip.html) 来帮助你忽略第一个元素,skipWhile 给你空数组,因为 [] !== null ,你可以添加这个条件
  • @user2216584 谢谢,我为我的选择器更新了主题。但是我的第一个空数组还在这里:/
  • 一个空数组不为空或未定义,因此它不会因您的条件而停止。您的 selectAll 是否有可能返回一个空数组?
  • @ukn 在我的减速器中,我添加了一个 console.log。并且只有一个对象,但是如果您有更好的方法从选择器中进行检查,我会尝试一下

标签: angular ngrx-store


【解决方案1】:

这看起来so familiar

我建议您 tap(console.log) 调试您的流,以便您了解那里发生了什么,例如:

this.publication$ = this.store$.pipe(
  tap(val => console.log('skipWhile', val, val == null)),
  skipWhile(val => val == null),
  select(PublicationFeatureStoreSelectors.selectAllPublicationFeatureItems),
  tap(value => console.log('filter', value, value !== undefined)),
  filter(value => value !== undefined),
);

输出将清楚地表明哪个条件通过以及出了什么问题。
祝你好运!

【讨论】:

    猜你喜欢
    • 2014-05-31
    • 1970-01-01
    • 2022-06-12
    • 2013-11-24
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2019-04-03
    相关资源
    最近更新 更多