我一直在学习 Angular 6,我对订阅方法和错误处理有疑问。
因此,在可观察对象上订阅函数的基本用法如下所示:
this.myService.myFunction(this.myArg).subscribe(
// Getting the data from the service
data => {
this.doSomethingWith(data);
},
err => console.log('Received an error: ', err),
() => console.log('All done!')
);
所以在这种情况下,错误可能是 500 错误或其他错误,但我想知道是否有办法从我的后端(我使用的是 PHP)发送我的数据,以便订阅函数将其识别为一个错误。例如,我的应用程序允许用户从一个特定的有限集(在我的例子中是所有口袋妖怪的集合)创建一个项目列表,所以如果他/她试图添加一个不存在的口袋妖怪,我希望我的后端返回一个错误。目前我正在返回一个像这样的 JSON 对象:{ "error"=> "you did something wrong"}
我在订阅函数的第一个参数中处理它。我想这很好,但如果有适当的错误处理方法,我认为最好利用它。
干杯!
最佳答案
尝试这样的事情:
import {
HttpEvent,
HttpHeaders,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHandler,
HttpRequest
} from '@angular/common/http';
this.myService.myFunction(this.myArg).subscribe(
// Getting the data from the service
data => {
this.doSomethingWith(data);
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 400:
console.log("400 Error")
break;
case 401:
console.log("401 Error")
break;
case 500:
console.log("500 Error")
break;
}
}
);
关于angular - 自定义订阅错误 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297115/