代码之家  ›  专栏  ›  技术社区  ›  Calidus

具有条件逻辑的嵌套订阅

  •  2
  • Calidus  · 技术社区  · 6 年前

    我有一个Crud Angular 5.5组件,它使用路由参数在各种模式(新建、编辑、查看)中自行设置。应该避免嵌套订阅,但我不确定如何这样做,因为我需要一些基本的条件逻辑。

        this.route.params.subscribe((params) => {
           this.action  = params.action;
           if (this.action  === 'new') {
               // get the formation need to make a new item
               this.service.getList().subscribe((data) = > this.list = data);
               // do stuff
           } else { 
               // view or edit a item
               this.service.getItem(params.id).subscribe((data) = > this.item = data);
               // do other stuff
           }
        });
    

    我试过使用切换映射,但我不确定是否真的好得多,因为现在我返回的是一个复杂类型的 observable<item> | observable<item[]> . 要做到这一点,必须有更好的表达方式。

    this.route.paramMap.switchMap((params: ParaMap) => {
       this.action = params.get('action');
       if (this.action === 'new) {
         return this.service.getList();
       } else {
         return this.service.getItem(params.get('id));
       }
    }).subscribe((data) => {
      if (this.action === 'new) {
         this.list = data;
         // do stuff
      } else {
         this.item = data;
         // do other stuff
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Tomasz Kula    6 年前

    const routes: Routes = [
      { path: '', component: IndexComponent },
      { path: 'create', component: CreateComponent },
      { path: ':id', children: [
          { path: '', component: ShowComponent },
          { path: 'update', component: UpdateComponent },
          { path: 'destroy', component: DestroyComponent },
        ] 
      }
    ];