【发布时间】:2018-11-10 18:01:50
【问题描述】:
我的客户端似乎没有从服务器捕获响应值并显示它。
这是我的组件代码:
export class MyComponent implements OnInit {
data: string;
constructor(private myService: MyService) {}
ngOnInit() {}
testCall() {
this.myService.getData().subscribe(data => this.data = data);
console.log("Data: " + this.data);
}
}
服务代码:
@Injectable()
export class MyService {
private url = 'http://localhost:5000/myproj/api/test';
constructor(private http: HttpClient) { }
// Get data from the server
getData(): Observable<string> {
console.log("in getData() method");
return this.http.get<string>(this.url)
.pipe(
catchError(this.handleError) // then handle the error
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return new ErrorObservable('Something went wrong; please try again later.');
};
}
请求到达服务器,服务器用响应正文中的数据进行响应,状态码为 200,您可以在 Internet Explorer 的开发者工具中看到:
但由于某种原因,当我调用服务方法getData() 时,angular 客户端代码会调用我定义的catchError() 方法,并打印:
Backend returned code 200, body was: [object Object]
ERROR Something went wrong; please try again later.
为什么服务端返回状态200(OK),而Angular客户端却调用catchError()方法?
编辑:
这是我的服务器端 API 代码:
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "text/plain")
public String testApi(HttpServletRequest request) {
System.out.println("in /test");
String response = "my response";
return response;
}
【问题讨论】:
-
做一个
body was ${JSON.stringify(error.error)},这样你就可以真正得到服务器在你的catch中发回的错误消息。 -
@RyanC 这是代码返回的错误:
{"error":{"description":"Invalid character","number":-2146827274,"stack":"SyntaxError: Invalid character\n at onLoad (eval code:2290:25)\n at ZoneDelegate.prototype.invokeTask (eval code:419:13)\n at onInvokeTask (eval code:4941:17)\n at ZoneDelegate.prototype.invokeTask (eval code:419:13)\n at Zone.prototype.runTask (eval code:188:21)\n at ZoneTask.invokeTask (eval code:495:17)\n at invokeTask (eval code:1536:9)\n at globalZoneAwareCallback (eval code:1562:17)"},"text":"my reponse"} -
所以您上面列出的 javascript 可以正确触发。 HTTP 调用返回错误,因此它正在进入该代码块。我确实看到您的响应中有一个
text对象,但是在您解决返回错误的后端问题之前,它始终会进入 catchError 函数。
标签: javascript angular typescript http spring-mvc