简体   繁体   中英

wait function to finish in Angular

I work with angular 7.

I want to wait function until finish before execute the rest of statement.

In my example I want to wait saveAttach function before execute the rest of statement:

 this.router.navigate(['/pages/sending']);

When I test my code the page is forwarded to sending page before the saveAttach function is running.

meaning this statement this.router.navigate(['/pages/sending']); is running first

and then this.dropzone.saveAttach(data.body[0].id); is running.

this is my code:

  public sendTransfer() {
    try {
     
            this.correspService.sendCorresp(this.correspondence).subscribe(data => {

            this.dropzone.saveAttach(data.body[0].id);

            this.router.navigate(['/pages/sending']);
            
            });

        

    } catch (exception) {
      console.log('sendCorresp() function error : ' + exception);
    }
  }

and in dropzone component I have this function:

 public  saveAttach(id: string) {
    let latt: Attachement[] = new Array<Attachement>();
    this.dropzoneservice.getDoc({
      page: 0,
      uuid: localStorage.getItem('uuid'),
      sort: ['id']
    }).subscribe((res: HttpResponse<IDocTemp[]>) => {
      for (let i = 0; i < res.body.length; i++) {
        let att = new Attachement();
        att.idDoc = res.body[i].id.toString();
        att.filename = res.body[i].filenamedoc;
        att.id = id;
       
        latt.push(att)
      }
      this.dropzoneservice.addAtt(latt).subscribe(data => {
        console.log("save saveAttach : ", data.body);
        
      })

    });
  }

Use await or thenable method:

this.dropzone.saveAttach(data.body[0].id)
  .then(() => {
     this.router.navigate(['/pages/sending']);
        
     });
  })


public saveAttach => async(id: string) {
  return new Promise(resolve => {
    let latt: Attachement[] = new Array<Attachement>();
    this.dropzoneservice.getDoc({
      page: 0,
      uuid: localStorage.getItem('uuid'),
      sort: ['id']
    }).subscribe((res: HttpResponse<IDocTemp[]>) => {
      for (let i = 0; i < res.body.length; i++) {
        let att = new Attachement();
        att.idDoc = res.body[i].id.toString();
        att.filename = res.body[i].filenamedoc;
        att.id = id;
       
        latt.push(att)
      }
      this.dropzoneservice.addAtt(latt).subscribe(data => {
        console.log("save saveAttach : ", data.body);
        resolve(); // <------------------
      })
    });
  })
}

You should return an Observable in your saveAttach function.

import { Observable } from 'rxjs';
import { mergeMap, tap } from 'rxjs/operators';

public saveAttach(id: string): Observable<any> {
    let latt: Attachement[] = new Array<Attachement>();

    return this.dropzoneservice.getDoc({
        page: 0,
        uuid: localStorage.getItem('uuid'),
        sort: ['id']
    }).pipe(
        mergeMap(() => {
            for (let i = 0; i < res.body.length; i++) {
                let att = new Attachement();
                att.idDoc = res.body[i].id.toString();
                att.filename = res.body[i].filenamedoc;
                att.id = id;
                
                latt.push(att);
            }
            return this.dropzoneservice.addAtt(latt);
        }),
        tap((data) => {
            console.log("save saveAttach : ", data.body);
        })
    );
}

Then, in sendTransfer you can pipe and execute you asynchronous function one after the other.

import { tap, mergeMap, catchError } from 'rxjs/operators';

public sendTransfer() {
    this.correspService.sendCorresp(this.correspondence).pipe(
        catchError((exception) => console.log('sendCorresp() function error : ' + exception)),
        mergeMap((data) => this.dropzone.saveAttach(data.body[0].id)),
        tap(() => this.router.navigate(['/pages/sending']))
    ).subscribe();
}

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