【发布时间】:2019-09-08 07:06:53
【问题描述】:
当我尝试从我的json-server 获取数据时出现此错误。baseURL 已定义并可通过我的浏览器访问,因此这方面没有问题。
欢迎提出任何建议。
dish.service.ts 中的代码
import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { baseURL } from '../shared/baseURL';
import { ProcessHTTPMsgService } from './process-httpmsg.service';
@Injectable({
providedIn: 'root'
})
export class DishService {
constructor(private http: HttpClient,
private processHTTPMsgService: ProcessHTTPMsgService) { }
getDishes(): Observable<Dish[]> {
return this.http.get<Dish[]>(baseURL + 'dishes')
.pipe(catchError(this.processHTTPMsgService.handleError));
}
getDish(id: string): Observable<Dish> {
return this.http.get<Dish>(baseURL + 'dishes/' + id)
.pipe(catchError(this.processHTTPMsgService.handleError));
}
getFeaturedDish(): Observable<Dish> {
return this.http.get<Dish[]>(baseURL + 'dishes?featured=true').pipe(map(dishes => dishes[0]))
.pipe(catchError(this.processHTTPMsgService.handleError));
在出错的情况下调用 process-httpmsg.service.ts
import { Injectable } from '@angular/core';
import { throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ProcessHTTPMsgService {
constructor() { }
public handleError(error: HttpErrorResponse | any) {
let errMsg: string;
if (error.error instanceof ErrorEvent) {
errMsg = error.error.message;
console.log('errMsg (is instanceof ErrorEvent): ', errMsg)
} else {
errMsg = `${error.status} - ${error.statusText || ''} ${error.message}`;
console.log('errMsg (is NOT instanceof ErrorEvent): ', errMsg)
}
return throwError(errMsg);
}
}
【问题讨论】:
-
你没有导入任何名为 ErrorEvent 的东西,你期望它来自哪里?这不是 Node/JavaScript 的原生对象,称为 ErrorEvent。
-
我认为 Alexander 错了,因为它是一个 js 对象。 developer.mozilla.org/en-US/docs/Web/API/ErrorEvent 我正在尝试找出问题所在,因为您的代码看起来很完美,但我不明白。如果您可以提供整个错误消息,那将很有帮助(折叠,未展开,太长且无用)
-
根据我的说法,您想要/应该构建的解决方案是基于 HTTPInterceptor 的解决方案,它可以从任何 http/https 调用中捕获错误,并且您还可以决定如何管理这些错误。
-
正如@jcuypers 已经提到的,您必须尝试使用拦截器,这是理想的方式。您在哪个平台上遇到此问题,您正在测试的设备上的操作系统版本是什么?端点是否安全 (https)?
-
你有问题吗?
标签: angular nativescript