Angular2 Observable and Promise

后端 未结 3 784
面向向阳花
面向向阳花 2021-02-02 07:01

I started using Angular2 Observable, but I can\'t find something similar to .then that I used with Promises.

This is what I want

相关标签:
3条回答
  • 2021-02-02 07:48

    When you call subscribe(...) a Subscription is returned which doesn't have a toPromise(). If you move the code from subscribe to map you can use toPromise() instead of subscribe

    return this._httpClient.post('LoginAction', credentials)
      .map(res => res.json())
      .map(user => {
        return new User(user);
      }).toPromise();
    

    and the caller will get a Promise where he can get the value using

    public login() {
        this._user = AuthService.getInstance().login(this._loginInfo)
        .then(result => {
          doSomething();
        });
    }
    

    but you get the same result if you omit `.toPromise() and the caller uses it like

    public login() {
        this._user = AuthService.getInstance().login(this._loginInfo)
        .subscribe(result => {
          doSomething();
        });
    }
    

    where the only difference is subscribe() instead of then() and if the user of the library prefers the reactive style he will prefer using subscribe() like he is used to.

    0 讨论(0)
  • 2021-02-02 07:49

    From Angular2 documentation

    We are advise to add this in rxjs-extension.ts

    ```
    // Observable class extensions 
       import 'rxjs/add/observable/of'; 
       import 'rxjs/add/observable/throw';
    
    // Observable operators 
       import 'rxjs/add/operator/catch'; 
       import 'rxjs/add/operator/debounceTime'; 
       import 'rxjs/add/operator/distinctUntilChanged'; 
       import 'rxjs/add/operator/do'; 
       import 'rxjs/add/operator/filter'; 
       import 'rxjs/add/operator/map'; 
       import 'rxjs/add/operator/switchMap'; 
    ```
    

    And import it at app.module.ts (Root Module) import './rxjs-extensions';

    This will help us to prevent further error.

    0 讨论(0)
  • 2021-02-02 07:58

    You need to import the Rx toPromise operator like

    import 'rxjs/add/operator/toPromise';
    

    Cheers!

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