如何使用Ngrx导航功能?

问题描述 投票:0回答:1

我从 NgRx 遇到了 navigation。阅读文档后,我的理解是,加载组件时会触发

effect
。但不幸的是,这种效果没有被触发。我已经与其他
effects
进行了测试,它们按预期触发

export class RouterEffects {

  private actions$ = inject(Actions);
  private routerFacade: RouterFacade = inject(RouterFacade);
  private shellFacade: ShellFacade = inject(ShellFacade);
  private appService: AppService = inject(AppService);
  private router = inject(Router);

  getProfile$ = createEffect(() =>
    this.actions$.pipe(
      navigation(LoginComponent, {
        run: (a: ActivatedRouteSnapshot, ...slices): Observable < Action > | Action | void => {
          console.log('hello')
          return this.appService.getProfile()
            .pipe(map((profile) => ({
              type: 'Load',
              todo: profile
            })))
        },
        onError: (a: ActivatedRouteSnapshot, e: any) => {
          console.log(e)
          return null
        }
      })
    ));
}

该效果也添加到独立应用程序配置中

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([httpInterceptor])),
    provideRouter(appRoutes),
    provideStore({
      router: routerReducer
    }),
    provideState({
      name: SHELL_FEATURE_KEY,
      reducer: shellReducer
    }),
    provideEffects([ShellEffects, RouterEffects]),
    provideRouterStore({
      //serializer:RouteSerializer
    }),
    provideStoreDevtools({
      // dev tool config
    })
  ],
};

我的问题是我做错了什么以及如何使

navigation
功能发挥作用

javascript angular ngrx ngrx-store ngrx-effects
1个回答
0
投票

试试这个

getProfile$ = createEffect(() =>
  this.actions$.pipe(
    navigation(LoginComponent, {
      run: (a: ActivatedRouteSnapshot, ...slices): Observable < Action > | Action | void => {
        console.log('effect triggered'); // Add this line
        return this.appService.getProfile()
          .pipe(map((profile) => ({
            type: 'Load',
            todo: profile
          })));
      },
      onError: (a: ActivatedRouteSnapshot, e: any) => {
        console.log(e);
        return null;
      }
    })
  ));

现在确保效果已正确添加到跑步者中。确保您已在 app.module.ts 或 bootstrap.ts 文件中导入了必要的模块和组件,如下所示:

import { store, effects } from '@ngrx/store';
import { RouterEffects } from './router.effects';

@NgModule({
  // ...
  effects: [RouterEffects],
  // ...
})
export class AppModule {
  // ...
}

此外,请确保正确订阅效果。如果您使用@ngrx/router-store包,则需要将效果添加到@ngrx/effects运行器。您可以在 app.component.ts 或单独的 app.effects.ts 文件中执行此操作,如下所示:

import { Actions, ofType } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { RouterEffects } from './router.effects';

@Component({
  // ...
})
export class AppComponent {
  constructor(private actions$: Actions, private store: Store) {
    this.actions$.pipe(ofType(RouterEffects)).subscribe();
  }
}

此外,检查浏览器控制台和网络区域中是否存在任何错误,这些错误可能表明单击浏览器中的检查选项(firefox、mozilla、chrome、brave 或 Microsoft Edge)时效果或路由器配置存在问题。揭示错误。

© www.soinside.com 2019 - 2024. All rights reserved.