Angular 5未显示来自服务器的响应值

时间:2018-05-31 16:44:26

标签: javascript angular typescript http spring-mvc

似乎我的客户端没有从服务器捕获响应值并显示它。

这是我的组件代码:

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的开发人员工具中看到:

enter image description here

但出于某种原因,当我调用服务方法getData()时,角度客户端代码调用我定义的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;
    }

3 个答案:

答案 0 :(得分:2)

响应正文不是正确的JSON格式,因此反序列化产生的“无效字符”错误。该服务期望正确形成JSON。

使用“application / json”更新您的API以返回有效的JSON对象,并返回一个对象,如以下帖子所示:Spring MVC - How to return simple String as JSON in Rest Controller

答案 1 :(得分:0)

您需要将console.log放在.subscribe()方法

 this.myService.getData().subscribe(data => {
     this.data = data;
     console.log(this.data);
});

答案 2 :(得分:0)

您必须在请求选项对象中将responseType设置为'text'。这是一个示例:

return this.http.get(`myApi/ExampleMethod/param`, { responseType: 'text' })
                .pipe(
                    catchError(
                        this.errorHandler.handleError.bind(this)
                    )
                 );