Angular 2: Convert Observable to Promise

后端 未结 7 623
耶瑟儿~
耶瑟儿~ 2020-11-27 18:00

Q) How do I convert the following observable to a promise so I can call it with .then(...)?

My method I want to convert to a promise:

相关标签:
7条回答
  • 2020-11-27 18:09

    You can convert Observable to promise just by single line of code as below:

    let promisevar = observable.toPromise()
    

    Now you can use then on the promisevar to apply then condition based on your requirement.

    promisevar.then('Your condition/Logic');
    
    0 讨论(0)
  • 2020-11-27 18:11

    rxjs6

    https://github.com/ReactiveX/rxjs/issues/2868#issuecomment-360633707

    Don't pipe. It's on the Observable object by default.

    Observable.of('foo').toPromise(); // this
    

    rxjs5

    import 'rxjs/add/operator/toPromise';
    import 'rxjs/add/operator/map';
    
    ...
    
    this._APIService.getAssetTypes()
    .map(assettypes => {
      this._LocalStorageService.setAssetTypes(assettypes);
    })
    .toPromise()
    .catch(err => {
      this._LogService.error(JSON.stringify(err));
    });
    
    0 讨论(0)
  • 2020-11-27 18:16

    observable can be converted to promise like this:

    let promise=observable.toPromise();
    
    0 讨论(0)
  • 2020-11-27 18:22

    A lot of comments are claiming toPromise deprecated but as you can see here it's not.

    So please juste use toPromise (RxJs 6) as said:

    //return basic observable
    const sample = val => Rx.Observable.of(val).delay(5000);
    //convert basic observable to promise
    const example = sample('First Example')
      .toPromise()
      //output: 'First Example'
      .then(result => {
        console.log('From Promise:', result);
      });
    

    async/await example:

    //return basic observable
    const sample = val => Rx.Observable.of(val).delay(5000);
    //convert basic observable to promise
    const example = await sample('First Example').toPromise()
    // output: 'First Example'
    console.log('From Promise:', result);
    

    Read more here.

    And please remove this wrong claim saying toPromise is deprecated.


    Note: Otherwise you can use .pipe(take(1)).toPromise but as said you shouldn't have any problem using above example.

    0 讨论(0)
  • 2020-11-27 18:26

    The proper way to make Observable a Promise, in your case would be following

    getAssetTypesPromise() Observable<any> {
      return new Promise((resolve, reject) => {
          this.getAssetTypes().subscribe((response: any) => {
            resolve(response);
          }, reject);
        });
    }

    0 讨论(0)
  • 2020-11-27 18:27

    you dont really need to do this just do ...

    import 'rxjs/add/operator/first';
    
    
    this.esQueryService.getDocuments$.first().subscribe(() => {
            event.enableButtonsCallback();
          },
          (err: any) => console.error(err)
        );
        this.getDocuments(query, false);
    

    first() ensures the subscribe block is only called once (after which it will be as if you never subscribed), exactly the same as a promises then()

    0 讨论(0)
提交回复
热议问题