我正在尝试使用observable进行以下操作,但我无法弄清楚最好的方法是做什么:
我正在使用http调用登录端点。此服务将返回令牌。我希望从APP中的2个不同点顺序执行2个不同的操作:当http解析时,我需要存储提供的令牌然后显示消息。我尝试了以下方法:
return this.http.get(this.config.getApi('login'), params)
.map(response => response.json())
.do((data) => {
// Store token here
// If it fails, throw error
// Tried Observable.throw here but the subscriber doesn't get it.
}).subscribe(
(data) => {
// Everything went fine
},
() => {
// Either the http request failed or
// the process of storing the token threw an error.
}
);
不幸的是,除非http调用失败,否则返回的observable的订阅者永远不会收到错误。我应该使用什么操作符代替?
感谢。
答案 0 :(得分:2)
您应subscribing
访问回复
this.http.get(this.config.getApi('login'), params)
.map(response => response.json())
.subscribe(data=>{
console.log(data);
});
答案 1 :(得分:1)
也许是这样的?
import { isDevMode } from '@angular/core';
import { _throw } from 'rxjs/observable/throw';
return this.http.get(this.config.getApi('login'), params)
.map(r => r.json())
.do(data => {
this.token = data; //an instance variable defined in your service class
if(isDevMode()) console.log(data) // display log only in devMode (why would you want to log something in console in production?! :D)
})
.catch(error => _throw(JSON.stringify(error));
Ofc你需要从外部(组件,警卫等)调用此方法,以便执行http请求
答案 2 :(得分:1)
根据我的理解,您想要这样做:
do http call
then do something else
if error
throw error
subscribe
handle success
handle error
我能想到的一种方法是使用flatMap
。重写代码
return this.http.get(this.config.getApi('login'), params)
.map(response => response.json())
.flatMap((data) => {
//do whatever you want to do ,
// lets say error = true if something went wrong
return error ?
Observable.throw('error message') :
Observable.of(data);
}).subscribe(...);
JSBIN链接了一个简单的插图