【问题标题】:Angular 5 is not displaying response value from serverAngular 5 不显示来自服务器的响应值
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 请检查我的编辑,这是我在服务器端的。
  • 更新了解决 API 问题的答案。核心返回一个对象,输出为“application/json”而不是纯文本。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多