首页 > 解决方案 > 带有可选 api 调用的 rxjs

问题描述

这是我的代码。我必须在提交表单时验证用户名和电子邮件。但是 userno 存在是基于所有用户通用的用户类型和电子邮件验证的条件。

这是代码

save()
{
    numexist:false;emailexist:false;
    
    if(type=="Manual")
    {      
           this.userService.IsUserNoExist(no).subscribe({
              next: (result: any)  => {            
                numexist=result;
              },
              error: (error:any) => {
                this.close();
              }
            });  
      }  //if
    
    //Email Check common for all user type  
    this.userService.IsEmailExist(email).subscribe({
              next: (result: any)  => {            
                emailexist=result;
              },
              error: (error:any) => {
                this.close();
              }
            });  
            
 if(numexist==false && emailexist==false)
    {  // Here comes before result come from email exist
               //Save
            }
            else
            {
              //nothify
            }               
 }

我已经编写了多个订阅方法..但是我必须检查两个条件过程保存..请让我知道我必须加入哪个操作员 forkjoin 不是可选情况请帮助我

标签: angularrxjs

解决方案


像这样的东西(未测试确切的语法):

userNoExists$ =  iif(()=> type==="Manual",
                     this.userService.IsUserNoExist(no).pipe(
                        tap((result: any)  => numexist=result),
                        catchError((error:any) => this.close())
                     ),
                     of(null)
              );

如果类型是“手动”,则调用服务,处理结果并发出值。否则,发出 null (或者这可能发出 false)。

有关更多信息,iif请参阅:https ://rxjs.dev/api/index/function/iif

然后

  emailExists$ = this.userService.IsEmailExist(email).pipe(
                  tap((result: any)  => emailexist=result),
                  catchError((error:any) => this.close())
               );

  save() {
     combineLatest([
         this.userNoExists$,
         this.emailExists$
     ]).pipe(
        map([numexist, emailexist]) => {
            if(numexist==false && emailexist==false)
            {  // Save 
            }
            else
            {
               //nothify
            }
        })
     ).subscribe();
  }

推荐阅读