ngrx 类型,@ngrx/effects

ngrx ofType, @ngrx/effects

我试图了解 typeof 效果在 ngrx 中是如何工作的, 如果我在我的应用程序模块中声明:

....

@NgModule({
    imports: [
        EffectsModule.forRoot([TodosEffectsService])
],

....

而且我肯定会写效果文件:

@Effect() createTodos$ = this.actions$
.ofType(CREATE_TASK)
    .map(() => {
        console.log('called');
            return { type: 'OTHER'};
});

@Effect() addTodos$ = this.actions$
.ofType(CREATE_TASK)
    .map(() => {
        console.log('called');
            return { type: 'OTHER'};
});

我试着理解,现在 运行 时间我发送一个动作 this.action$ 被订阅并且每次执行 ofType 来匹配类型? 或 ofType 一旦执行!?

如果它调用一次,当我发送动作时效果如何知道每次 效果到 subscribe/execute?

谢谢大家!

简而言之,当 .ofType() 被调用时,它会订阅操作的源流并将匹配的操作推送到结果流。所以确实调用了一次。

如果我们查看 source code,我们会发现在底层 ofType 使用 rxjs 库的 filter 运算符,这意味着 this.action$.ofType(CREATE_TASK) 可以展开为

this.action$.filter(action => action.type === CREATE_TASK)

关于 filter 工作原理的描述可以从 rxjs docs:

中找到

Similar to the well-known Array.prototype.filter method, this operator takes values from the source Observable, passes them through a predicate function and only emits those values that yielded true.

值得注意的是,您的每个效果都将一个可观察对象 (this.action$) 作为输入,并且 returns 一个新的可观察对象,在初始化效果时仅订阅一次。返回的 observable 定义了输入 observable 的动作如何转换的方式,但它不会影响源 observable 本身。

在您的示例中 ofType() 方法 returns 一个新的可观察对象 "listens" 到 this.action$ 可观察对象,并且仅发出满足条件 action.type === CREATE_TASK 的操作。然后是 map 运算符,它还 returns 一个新的可观察对象,它 "listens" 到 ofType() 调用返回的可观察对象,并根据你传递的投影函数。但是所有这些可观察对象仅在初始化时创建一次,当您分派操作时,它们只是 "flow" 通过可观察对象,进行过滤和转换。

您可能还想更加熟悉 rxjs。我建议您查看 "You will learn RxJS" André Staltz 的演讲,它应该让您对什么是可观察量及其工作原理有一个直觉。

this.actions$ .ofType(CREATE_TASK) 将在您的 reducer case 执行后每次调度您的操作时调用。 像 还原剂

switch(action) {
case youractionsname.CREATE_TASK : {
// pure function logic here
   }
}

首先会执行 reducer,然后它会查看效果,如果你有任何类型为 'CREATE_TASK' 的效果。 在订阅模式中,无论您订阅什么,都将是回调函数,它会根据条件存储在引擎盖下的数组中。当您根据条件调度操作时,所有函数都会调用满足条件的人。

关键是ofType没有在ngrx/effects里面的Actions class中导出 所以你可以像下面这样使用它: 1- 从 ngrx/effects 导入类型,即

import { Injectable } from "@angular/core";

import { Effect, Actions, ofType } from "@ngrx/effects";
import * as omid from "@ngrx/effects";
import { of } from "rxjs";
import { map, switchMap, catchError } from "rxjs/operators";
@Injectable()
export class PizzasEffects {
  constructor(
    private actions$: Actions,
    private pizzaService: frtomServices.PizzasService
  ) {}

  @Effect()
  LoadPizzas$ = this.actions$.pipe(
    ofType(pizzaActions.LOAD_PIZZAS),
    switchMap(() => {
      return this.pizzaService.getPizzas().pipe(
        map(pizzas => new pizzaActions.LoadPizzasSuccess(pizzas)),
        catchError(error => of(new pizzaActions.LoadPizzasFail(error)))
      );
    })
  );
}

您还可以从每个效果调度一组动作。

Read this article from medium