[英]Angular 2 - Possible to subscribe to http errors in the 'calling' component?
I'm having trouble retrieving the error from the service. 我无法从服务中检索错误。 My component is calling a service and I want to subscribe to any errors that might be returned. 我的组件正在调用服务,我想订阅可能返回的任何错误。 However, it seems like I'm not allowed to subscribe on the calling method. 但是,似乎不允许我订阅调用方法。
public getMethods(v) {
if(v != null) {
return this._http.get('http:localhost/testservice', {
method: 'GET',
headers: new Headers([
'Accept', 'application/json',
'Content-Type', 'application/json'
])
})
.map(res => (res.json()))
.map((method: any) => {
if(method) {
let result: Array<string> = [];
var list = method.List;
list.forEach(v => {
result.push(v);
})
return result;
}
})
.subscribe(data => {
this._dataStore.mn= data;
this._mnObserver.next(this._dataStore.mn);
},
error => {
**// I want to retrieve this error in the 'calling' component**
return error;
});
}
else {
console.error("Get names. V was null");
}
In the component: This does not work: 在组件中:这不起作用:
this._mnService.getMethods(v), error => {
alert("error in da house");
};
This does not work: 这不起作用:
this._mnService.getMethods(v).subscribe( error => {
alert("error in da house");
});
So, what would work? 那么,什么可行? Thanks! 谢谢! :) :)
You need to refactor a bit your method: 您需要重构一下您的方法:
public getMethods(v) {
if(v != null) {
return this._http.get('http:localhost/testservice', {
method: 'GET',
headers: new Headers([
'Accept', 'application/json',
'Content-Type', 'application/json'
])
})
.map(res => (res.json()))
.map((method: any) => {
if(method) {
let result: Array<string> = [];
var list = method.List;
list.forEach(v => {
result.push(v);
})
return result;
}
});
} else {
console.error("Get names. V was null");
}
}
This way you will receive the error when subscribing on the observable: 这样,您在订阅可观察项时将收到错误:
this._mnService.getMethods(v).subscribe((data) => {
}, error => {
alert("error in da house");
});
What is a bit strange in your code is that you subscribe in the getMethods
method. 您的代码中有些奇怪的是您订阅了getMethods
方法。 So you don't return an observable for the request but a subscription. 因此,您不会为请求返回可观察到的内容,而是返回订阅。
If you want to trigger the _mnObserver
when the response is there, you could leverage the do
operator instead. 如果要在响应存在时触发_mnObserver
,则可以改用do
运算符。 Here is a sample: 这是一个示例:
public getMethods(v) {
if(v != null) {
return this._http.get('http:localhost/testservice', {
method: 'GET',
headers: new Headers([
'Accept', 'application/json',
'Content-Type', 'application/json'
])
})
.map(res => (res.json()))
.map((method: any) => {
if(method) {
let result: Array<string> = [];
var list = method.List;
list.forEach(v => {
result.push(v);
})
return result;
}
})
.do(data => { // <-------
this._dataStore.mn= data;
this._mnObserver.next(this._dataStore.mn);
});
} else {
console.error("Get names. V was null");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.