简体   繁体   English

如何将订阅从组件移动到解析

[英]How to move subscription from component to resolve

In my Angular app in my component i'm making two subscription to two Observables with switchMap that gets data from two API, when the component is opened i have to show a skeleton or a loader and i would prevent it, so i've just read about the Resolve which as i understand preload the data and then activate the route.在我的组件中的 Angular 应用程序中,我使用 switchMap 对两个 Observables 进行了两次订阅,从两个 API 获取数据,当组件打开时,我必须显示一个骨架或一个加载器,我会阻止它,所以我只是阅读有关解决方案,据我所知,预加载数据然后激活路线。

So i was wondering on how could i move the following subscription from ngOnInit to a Resolver所以我想知道如何将以下订阅从 ngOnInit 移动到解析器

Here is how my ngOnInit looks like now这是我的 ngOnInit 现在的样子

  ngOnInit(): void {
    this.menuService
      .menu(this.idNegozio, this.piva, 'IT')
      .pipe(
        switchMap((menu) =>
          forkJoin([
            of(menu),
            this.pluService.plu(this.idNegozio, this.piva, 'IT'),
          ])
        )
      )
      .subscribe(([menu, plus]) => {
        this.menu = menu;
        this.plus = plus;
        this.filterPlu(menu[0].id);
        if (this.filteredPlu.length) {
          this.ready = true;
        }
      });
  }

And that same component is used in three routes:并且在三个路由中使用了相同的组件:

  {
    path: 'asporto',
    component: ProductsComponent,
    canActivate: [ItemsGuardService]
  },
  {
    path: 'takeaway',
    component: ProductsComponent,
  },
  {
    path: 'ecom',
    component: ProductsComponent,
  },

Create a resolver创建解析器

 @Injectable() export class MenuResolver implements Resolve<Menu>{ constructor(private menuService: MenuService, private pluService: PluService) {} resolve(route: ActivatedRouteSnapshot): Observable<Menu> { const piva = route.parent.params.piva; const negozio = route.parent.params.negozio; return this.menuService .menu(negozio, piva, 'IT') .pipe( switchMap((menu) => forkJoin([ of(menu), this.pluService.plu(negozio, piva, 'IT'), ]) ), map(([menu, plus]) => ({ menu, plus })) ); } }

Use it in your routes definition and provide it in your parent module在你的路由定义中使用它并在你的父模块中提供它

 const routes: Routes = [ { path: '', resolve: { menu: MenuResolver }, component: Component, } ]; @NgModule({ imports: [ RouterModule.forChild(routes), ], providers: [ MenuResolver, ] }) export class MyModule { }

Then get it in your component via ActivatedRoute然后通过 ActivatedRoute 将其放入您的组件中

 export class MyComponent { menu: Menu; plus: MenuDetails; constructor(private route: ActivatedRoute){} ngOnInit() { const menuData = this.route.snapshot.data.menu; this.menu = menuData.menu; this.plus = menuData.plus; } }

You will have to add the resolver to all of the concerned routes, and use it the same way in the components您必须将解析器添加到所有相关路由,并在组件中以相同的方式使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM