Как дождаться функции, внутри которой есть Observable - PullRequest
1 голос
/ 05 мая 2020
 async  ngOnInit(){
    console.log('ngOnInit');
    var p1 =  this.Promisefun();
    Promise.all([p1]).then(()=>{
      this.PrintAfterAll();
    });

  }

  PrintAfterAll(){
    console.log('PrintAfterAll');
  }
 async  Promisefun(){
    const observable = new Observable<string>(observer => {
      setTimeout(() => {
        observer.next('value1');
        observer.next('value2');
        observer.next('value3');
        observer.complete();
      },100);
    });

    observable.subscribe( result => {
      console.log(result);
    });
  }

вывод

PrintAfterAll app.component.ts: 36 значение1 app.component.ts: 36 значение2 app.component.ts: 36 значение3

- Ожидаемый результат app.component.ts: 36 значение1 app.component.ts: 36 значение2 app.component.ts: 36 значение3 PrintAfterAll

Хотите вызвать функцию PrintAfterAll после того, как Promisefun завершит всю подписку внутри нее.

1 Ответ

0 голосов
/ 05 мая 2020

Вы можете преобразовать Observable в Promise с помощью toPromise function

В вашем примере вам нужно будет добавить Promisefun с return observable.toPromise();

async function ngOnInit() {


  var p1 = this.Promisefun();

  Promise.all([p1]).then(() => {
    this.PrintAfterAll();
  });

}

function PrintAfterAll() {
  console.log('PrintAfterAll');
}

async function Promisefun() {

  const observable = new rxjs.Observable(observer => {
    setTimeout(() => {
      observer.next('value1');
      observer.next('value2');
      observer.next('value3');
      observer.complete();
    }, 100);
  });

  observable.subscribe(result => {
    console.log(result);
  });

  return observable.toPromise();
}

ngOnInit();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>
...