我开始使用Angular2 Observable
,但我找不到类似的东西.then
,我用用Promises
。
这就是我要完成的。
public login() {
this._user = AuthService.getInstance().login(this._loginInfo);
}
return this._httpClient.post('LoginAction', credentials)
.map(res => res.json())
.subscribe(user => {
return new User(user);
});
有了promise,login
函数将返回Promise,最终将转换为服务器的实际响应。但是使用Observable,这将无法正常工作。
有没有办法做类似的事情?我想避免需要把内部认购的component
的login
功能。我希望能够完成服务中的所有工作,并将实际对象返回给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);
});
通过这样做,我的组件将获得对象(这是它所需要的),并且在服务中我可以做其他事情(例如,一旦我登录他,将用户保存到localstorage)。
然后我切换到Promise
,因为与这样做Observable
不起作用(或者我做错了)?
我看到返回的对象是Observable的(在调用toPromise之前),但是我确实没有看到toPromise
函数。
当您致电时subscribe(...)
,Subscription
会传回没有的toPromise()
。如果将代码从subscribe
移到map
,则可以使用toPromise()
代替subscribe
return this._httpClient.post('LoginAction', credentials)
.map(res => res.json())
.map(user => {
return new User(user);
}).toPromise();
呼叫者将获得一个Promise
他可以使用来获得价值的地方
public login() {
this._user = AuthService.getInstance().login(this._loginInfo)
.then(result => {
doSomething();
});
}
但是如果省略`.toPromise(),并且调用方像这样使用它,则会得到相同的结果
public login() {
this._user = AuthService.getInstance().login(this._loginInfo)
.subscribe(result => {
doSomething();
});
}
唯一的区别在于subscribe()
,then()
并且如果库的用户更喜欢反应式样式,那么他将更喜欢subscribe()
像过去那样使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句