typescript 类型 '"" 上不存在属性 'error' | 承诺<任何>'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43453790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Property 'error' does not exist on type '"" | Promise<any>'
提问by tofu
I'm trying to add some error handling to a service, following the Angular guide.
我正在尝试按照 Angular指南为服务添加一些错误处理。
Relevant snippet:
相关片段:
private handleError (error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
However, I'm getting a TypeScript error:
但是,我收到了 TypeScript 错误:
error TS2339: Property 'error' does not exist on type '"" | Promise<any>'.
Property 'error' does not exist on type '""'.
error TS2339: Property 'error' does not exist on type '"" | Promise<any>'.
Property 'error' does not exist on type '""'.
I can understand whyit's happening-- error.json()
returns a Promise<any>
and then the subsequent line with body.error
wouldn't work because there is no error
property. However, it seems like it should expect a JSON object to be returned from .json()
. Why is that, and what am I missing that the Angular guide isn't?
我可以理解为什么会发生这种情况 -error.json()
返回 aPromise<any>
然后随后的行 withbody.error
将不起作用,因为没有error
属性。但是,它似乎应该期望从.json()
. 为什么会这样,我错过了什么 Angular 指南不是?
回答by Marcelo Mason
Same thing just happened to me. This happens when you fail to import the Response object.
同样的事情刚刚发生在我身上。当您无法导入 Response 对象时,就会发生这种情况。
import { Response } from '@angular/http';
回答by Nitzan Tomer
No, it won't work because you wrote:
不,它不会工作,因为你写道:
const body = error.json() || '';
Which means that body
can be an empty string, and a string doesn't have the error
property.
这意味着body
可以是空字符串,而字符串没有该error
属性。
This should be better:
这应该更好:
const body = error.json() || { error: null };
Edit
编辑
Oh, error.json()
returns a Promise
, which means that you won't be able to use this synchronous block, instead you'll need to:
哦,error.json()
返回 a Promise
,这意味着您将无法使用此同步块,而是需要:
error.json().then(body => {
if (!body) {
body = "";
}
const err = body.error || JSON.stringify(body);
const errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
});
回答by Thomas PAPIN
I had the same issue, I finally found this solution.
我有同样的问题,我终于找到了这个解决方案。
.catch(error => {
let errMsg: string;
const body = JSON.parse(error._body);
if (body) {
errMsg = body.error
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Promise.reject(errMsg);
});