标签: ngrx-effects

NgRx Effects loaded twice

I have a simple feature module, which provides services and imports its own stats fragment as a feature:

@NgModule({
  imports: [
    CommonModule,
    StoreModule.forFeature('alarms', alarmsReducer, { initialState: alarmsInitialState }),
    EffectsModule.forFeature([AlarmsEffects])
  ],
  declarations: [],
  providers: [
    AlarmsFacade,
    AlarmsService
  ]
})
export class AlarmsModule {
}
Run Code Online (Sandbox Code Playgroud)

And I'm importing this module in two other modules, a page that needs to have access to the services, and AppModule as I need to import it here in order to have the state initialized properly.

When …

ngrx ngrx-effects angular

6
推荐指数
2
解决办法
3344
查看次数

NgRx:从商店获取数据但未定义

亲爱的 Stackoverflow 社区。

我是 NgRx 的新手,并试图找出它是如何工作的。我创建了一个应用程序 - 基于 Angular 6、Firebase 和 NgRx 的简单商店列表。

我在名为的集合中添加了几个项目,Product并尝试通过 ngrx 模式获取它们。似乎我做得很好 - 我已经获取了项目作为有效载荷,GET_PRODUCTS_SUCCESS但我无法将它们放入视图中进行显示,产品未定义。我尝试通过两种方式进行:

this.store.select(getProducts).subscribe(products => {
  console.log('products', products); // undefined
});
Run Code Online (Sandbox Code Playgroud)

 this.products = this.store.select(getProducts); // Store
Run Code Online (Sandbox Code Playgroud)

在第二种方式中,我只是得到了一个完整的商店......下面的代码。

product.actions.ts

import { Action } from '@ngrx/store';
import { Product } from '../../models/product.model';

export const GET_PRODUCTS = 'Get_products';
export const GET_PRODUCTS_SUCCESS = 'Get_products_success';

export class GetProducts implements Action {
  readonly type = GET_PRODUCTS;
  constructor(public payload = '') {}
}

export class GetProductsSuccess implements …
Run Code Online (Sandbox Code Playgroud)

typescript ngrx ngrx-effects angular ngrx-store

6
推荐指数
1
解决办法
8878
查看次数

NGRX 效果中的访问状态

如何在效果中访问我的状态?我当前的效果实现(如下所示)是在SEARCH_REUQUEST分派动作时触发的。但是,在调用我的搜索服务以启动 HTTP 请求之前,我想访问一个状态以获取一些搜索参数。

@Effect()
SearchRequest$ = this.actions$
  .ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST)
  .pipe(
    switchMap((action: fromSearchActions.SearchRequest) => {
      return this.searchService
        .search(action.payload, action.enrichmentId)
        .pipe(
          map(response => {
            console.group("SEARCH effects");
            console.log(response);
            console.groupEnd();
            return new fromSearchActions.SearchRequestSuccess(response);
          }),
          catchError(error =>
            of(new fromSearchActions.SearchRequestFail(error))
          )
        );
    })
  );
Run Code Online (Sandbox Code Playgroud)

显然,我可以在这里利用一个 RxJS 运算符,但我似乎无法理解如何修改现有的效果实现以合并它。

@Effect()
SearchRequest$ = this.actions$
  .ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST)
  .withLatestFrom(this.featureStore.select(fromFeature.getCurrentSearchPageOptions))
  .pipe(
      switchMap((// How should this change? //) => { //Error
        return this.searchService
          .search(action.payload, action.enrichmentId, pageOptions)
          .pipe(
            map(response => {
              console.group("SEARCH effects");
              console.log(response);
              console.groupEnd();
              return new fromSearchActions.SearchRequestSuccess(response);
            }),
            catchError(error =>
              of(new fromSearchActions.SearchRequestFail(error))
            ) …
Run Code Online (Sandbox Code Playgroud)

ngrx ngrx-effects angular ngrx-store-4.0

6
推荐指数
2
解决办法
4462
查看次数

ngrx 效果抛出“调度无效操作:未定义”

在对话响应的条件下,我对注销确认有这种效果,但出现以下错误:

错误错误:效果“AuthEffects.logoutConfirmation$”调度了一个无效的动作:未定义

错误类型错误:操作必须是对象

效果如下:

@Effect()
logoutConfirmation$ = this.actions$
    .ofType<Logout>(AuthActionTypes.Logout)
    .pipe(
      map(action => {
        if (action.confirmationDialog) {
          this.dialogService
            .open(LogoutPromptComponent)
            .afterClosed()
            .pipe(
              map(confirmed => {
                if (confirmed) {
                  return new LogoutConfirmed();
                } else {
                  return new LogoutCancelled();
                }
              })
            );
        } else {
          return new LogoutConfirmed();
        }
      })
    );
Run Code Online (Sandbox Code Playgroud)

它在激活确认对话框时起作用,我想这是对话框响应的地图有问题,一直试图理解它但找不到方法。任何人都有这方面的线索?

rxjs ngrx ngrx-effects angular

6
推荐指数
2
解决办法
1万
查看次数

Angular NgRx - 继续轮询仅第一次调用的服务的效果

我有一个应用程序,我刚刚在其中添加了 NgRX,我希望在其中使用效果来打开和关闭轮询。

示例大纲

我关注了这篇文章,这似乎是一个很好的方法。我在这里有一个简化的例子,大部分代码在app.effects.ts.

与示例类似,我有效果startPolling$,stopPolling$continuePolling$,但我使用的是较新的createEffect工厂方法。

另外,我已经移动了delay(2000)上面的takeWhile(),因为我发现如果服务调用抛出错误,catchError(err => of(appActions.getDataFail(err)))将导致效果进入一个连续的非常快速的循环而没有延迟。

开始和停止按钮调度轮询开始和停止......

public start() {
    console.log('dispatching start');
    this.store.dispatch(appActions.startPolling());
  }

  public stop() {
    console.log('dispatching stop');
    this.store.dispatch(appActions.stopPolling());
  }
Run Code Online (Sandbox Code Playgroud)

我的问题

我有一些控制台日志,所以我们可以看到发生了什么。

当我们单击开始按钮时(只是一次),我可以看到轮询开始,并按预期继续。例如,我可以一遍又一遍地看到以下内容...

dispatching start
app effect started polling
app.service.getData
app effect continue polling
app.service.getData
app effect continue polling
app.service.getData
app effect continue polling
Run Code Online (Sandbox Code Playgroud)

完美的。

当我停下来时,我看到

dispatching stop
app effect stop polling
Run Code Online (Sandbox Code Playgroud)

也正确。 …

rxjs ngrx ngrx-effects angular

6
推荐指数
1
解决办法
2660
查看次数

传递给“selectId”实现的实体返回未定义。您可能应该提供自己的“selectId”实现

警告就在这里

在此输入图像描述

https://github.com/rokudo5262/phone这是我的项目,
我想加载智能表中的品牌列表,但收到警告,
我尝试修复,但警告仍然存在,请帮助
Brands-features.selector.ts

import { createFeatureSelector } from '@ngrx/store';
import { State, FeatureKey } from '../reducers';

export const selectBrandsState = createFeatureSelector<State>(FeatureKey);
Run Code Online (Sandbox Code Playgroud)

品牌.selector.ts

import { createSelector } from '@ngrx/store';
import { selectBrandsState } from './brands-features.selector';
import { BrandsReducer } from '../reducers';
import { brandAdapter } from '../states/brands.state';

export const selectBrandEntitiesState = createSelector(
  selectBrandsState,
  state => state[BrandsReducer.brandsFeatureKey],
);

export const {
  selectIds: selectBrandIds,
  selectEntities: selectBrandEntities,
  selectAll: selectAllBrands,
  selectTotal: selectTotalBrands,
} = brandAdapter.getSelectors(selectBrandEntitiesState);

export const BrandSelectors = {
  selectBrandEntitiesState,
  selectBrandIds,
  selectBrandEntities, …
Run Code Online (Sandbox Code Playgroud)

ngrx ngrx-effects angular ngrx-store ngrx-entity

6
推荐指数
2
解决办法
9155
查看次数

NgRx效果,发生失败,不接受新的动作

@Injectable()
export class UserEffects {
  constructor(
    private store$: Store<fromRoot.State>,
    private actions$: Actions,
    private router: Router,
    private chatService: ChatService,
    private authService: AuthService,
    private db: AngularFireAuth,
    private http: HttpClient
  ) { }

  @Effect()
  login$: Observable<Action> = this.actions$.pipe(
    ofType(UserActions.LOGIN),
    switchMap((action: UserActions.LoginAction) =>
      from(this.db.auth.signInWithEmailAndPassword(action.payload.email, action.payload.password)),
    ),
    // switchMapTo(from(this.db.auth.currentUser.getIdToken())),
    switchMapTo(from(this.db.authState.pipe(
      take(1),
      switchMap((user)=>{
        if (user)
          return from(user.getIdToken());
        else
          return of(null);
      })
    ))),
    switchMap(token => this.http.post(environment.apiUrl + '/api/login', { token: token })),
    tap((response: any) => {
      if (response.valid === 'true') {

        localStorage.setItem('token', response.token);

        this.router.navigate(['dash']);

      }
    }),
    map(response …
Run Code Online (Sandbox Code Playgroud)

javascript rxjs ngrx ngrx-effects angular

6
推荐指数
1
解决办法
1936
查看次数

如何在 NgRx Effect 中调用另一个调度操作?

概述:用户按下 + 按钮添加购物车中的商品,数量增加 1。(this.store.dispatch(CartActions.IncrementCoin({name}))

之后,调用下一个方法
this.store.dispatch(CartActions.updateTotalPrice());

这是为了更新所有产品的总价,现在我想将第二个操作调用移动到一个效果,因为第二个操作是增量操作的副作用。但我该怎么做呢?我在网上没有看到这个问题的答案,所以我在这里问。

这是我想要实现的效果,因此它会监听 incementCoin 操作。此后,它需要触发 updateTotalPrice 操作。我该如何构建这个?

在此输入图像描述

在此输入图像描述

在此输入图像描述

更新

已实施以下解决方案。此效果现在可聆听 5 种不同的动作!

在此输入图像描述

ngrx ngrx-effects angular

6
推荐指数
1
解决办法
5887
查看次数

如何测试返回的 Observable 是否为 EMPTY

我有一个效果,在一种情况下返回一个EMPTYObservable。我正在尝试测试这个案例,但我似乎不知道如何测试EMPTYObservable?我的代码如下:

效果:

   effect$ = createEffect(() =>
    this.actions$.pipe(
      ofType(someAction),
      mergeMap(([action]) => {
        if (someCondition) {
          return EMPTY <-- this is what I am trying to test
        }
        return someServiceCall.pipe(
          map((offers) => //dispatch some action,
          catchError((error: string) => // dispatch another action),
        )
      }),
    ),
  )
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试尝试,但失败了

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

考虑到测试中已经满足条件:

  it('should return EMPTY when ...', (done) => {
    actions$ = of(someAction)
    effects.effect$.subscribe((res) => {
      expect(res).toEqual(never)
      done() …
Run Code Online (Sandbox Code Playgroud)

jasmine rxjs karma-jasmine ngrx-effects angular

6
推荐指数
1
解决办法
1万
查看次数

“NullInjectorError:没有 t 的提供者!” @ngrx 错误

我有一个使用ngrx 12.0.0的Angular 12.0.2应用程序。当我运行应用程序并访问延迟加载模块的路由时,出现以下错误。

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(t)[t -> InjectionToken @ngrx/effects Feature Effects -> [object Object] -> t -> t -> t -> t -> t -> t]: 
  NullInjectorError: No provider for t!
NullInjectorError: R3InjectorError(t)[t -> InjectionToken @ngrx/effects Feature Effects -> [object Object] -> t -> t -> t -> t -> t -> t]: 
  NullInjectorError: No provider for t!
    at fs.get (main.js:1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我已经正确设置了ngrxEffects请看下面显示效果的代码。这是模块中提供UserService程序的一个条目。

该错误没有说明缺少哪个提供者。 …

ngrx ngrx-effects angular

6
推荐指数
1
解决办法
8441
查看次数