简体   繁体   中英

wait for subscribe to finish and call save in angular6?

I have to complete validation functions before calling the save function. I am calling API (Async in C#) for validation function and it does not wait until the return result and proceeding in to save which is wrong.

submit() {        
       this.validateBeforeSave();
       this.Save();        
      }
    
     validateBeforeSave()
     {
      // Here calling API action ( used Async and Await in C#)
          forkJoin([Action1URL, Action2URL])             
        .subscribe(([Action1Data, Action2Data]) => {
           this.ValidateData(
              Action1Data,
              Action2Data
            );
           // Don't want to call save here. should be called separately.
        });   
     }
     
     Save()
     {
     // Saving data.
     
     }

Please let me know how to wait for the return result from the subscribe and then call the save function? And how can I call save function without placing inside subscribe?

It's not possible to call save() function separately after subscribe, While it hits subscribe it will redirect to next line after execution of all lines next to validateBeforeSave() function and then code inside subscribe will be executed.


submit() {        
       this.validateBeforeSave();
      
      }
    
     validateBeforeSave()
     {
      // Here calling API action ( used Async and Await in C#)
          forkJoin([Action1URL, Action2URL])             
        .subscribe(([Action1Data, Action2Data]) => {
           this.ValidateData(
              Action1Data,
              Action2Data
            );
           this.Save();        
        });   
     }
     
     Save()
     {
     // Saving data.
     
     }

Assuming Validate method returns a boolean that lets you know if you should save or not.

submit() {
      this.validateBeforeSave()
        .subscribe((isFormValid: boolean) => {
          if (isFormValid) { // repending on result of ValidateData
            this.Save();
          }
        });
    }
    
    validateBeforeSave(): Observable < boolean > { // returns observable
      // Here calling API action ( used Async and Await in C#)
      forkJoin([Action1URL, Action2URL])
      .pipe(map([Action1Data, Action2Data]) => {
        return this.ValidateData(Action1Data, Action2Data); // returning boolean returned from validateData
      });
    }
    
    Save() {
      // Saving data
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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