Angular2 Observable和Promise

Ned*_*Ned 35 promise observable rxjs angular

我开始使用Angular2 Observable,但我找不到类似于.then我使用的东西Promises.

这就是我想要完成的.

来自header.component.ts的代码

public login() {
    this._user = AuthService.getInstance().login(this._loginInfo);
}
Run Code Online (Sandbox Code Playgroud)

来自auth.service.ts的代码

return this._httpClient.post('LoginAction', credentials)
  .map(res => res.json())
  .subscribe(user => {
    return new User(user);
  });
Run Code Online (Sandbox Code Playgroud)

使用promises, login函数将返回Promise,最终将转换为来自服务器的实际响应.但是使用Observable这不起作用.

有没有办法做类似的事情?我想避免将subscribe放在里面componentlogin函数中.我希望能够在服务中完成所有工作,并将实际对象返回到component.

此外,我试图创建Promise,用toPromise的,但我不断收到toPromise is not a function.

ps _httpClient是我对angular2 http的包装,我在其中通过添加一些标题等来准备请求.

编辑

return this._httpClient.post('LoginAction', credentials)
  .map(res => res.json())
  .toPromise().    <-- i keep getting that it is not a function
  then(user => {
    return new User(user);
});
Run Code Online (Sandbox Code Playgroud)

通过这样做,我的组件将获得对象(这是它需要的),并且在服务中我可以做更多的事情(比如一旦我登录他就将用户保存到localstorage).

我切换到了Promise,因为做同样的事情Observable不起作用(或者我做错了)?

我看到返回的对象是Observable(在调用toPromise之前),但我确实没有看到toPromise函数.

Gün*_*uer 33

当你打电话给subscribe(...)一个Subscription没有的时候toPromise().如果您将代码移动subscribemap,则可以使用toPromise()而不是subscribe

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

并且调用者将获得Promise他可以使用的值

public login() {
    this._user = AuthService.getInstance().login(this._loginInfo)
    .then(result => {
      doSomething();
    });
}
Run Code Online (Sandbox Code Playgroud)

但如果省略`.toPromise()并且调用者使用它就会得到相同的结果

public login() {
    this._user = AuthService.getInstance().login(this._loginInfo)
    .subscribe(result => {
      doSomething();
    });
}
Run Code Online (Sandbox Code Playgroud)

唯一的区别在于,subscribe()而不是then()如果图书馆的用户更喜欢他喜欢使用的反应式,他subscribe()就像他习惯的那样.


dhe*_*ran 22

您需要导入Rx toPromise运算符

import 'rxjs/add/operator/toPromise';
Run Code Online (Sandbox Code Playgroud)

干杯!