Angular 6:如何在进行 http 调用时将响应类型设置为文本

新手上路,请多包涵

我试图向spring rest API发出http请求。API返回一个字符串值(“成功”或“失败”)……但我不知道如何在调用API时将响应类型设置为字符串值。 . 它的抛出错误作为后端返回代码200,正文是:[object Object]

我的角度代码如下所示,

order.service.ts

 import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ProductSearch } from '../_models/product-search';
import { ProductView } from '../_models/product-view';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ErrorHandlerService } from './error-handler.service';
import { Category } from '../_models/category';

@Injectable({
  providedIn: 'root'
})
export class OrderService {

  constructor(private http: HttpClient, private errorHandlerService: ErrorHandlerService) { }

addToCart(productId: number, quantity: number): Observable<any> {
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    console.log("--------order.service.ts----------addToCart()-------productId:"+productId+":------quantity:"+quantity);
     return this.http.post<any>('http://localhost:8080/order/addtocart',
              { dealerId: 13, createdBy: "-1", productId: productId, quantity: quantity},
              {headers: headers})
              .pipe(catchError(this.errorHandlerService.handleError));
    }
}

错误处理程序.service.ts

 import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ErrorHandlerService {

  constructor() { }

  public 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 throwError(
      'Something bad happened; please try again later.');
  };

}

原文由 rahul shalgar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 527
2 个回答

您不应该使用这些标头,标头确定您要发送的类型,并且您显然正在发送一个对象,这意味着 JSON。

相反,您应该将选项 responseType 设置为 text

 addToCart(productId: number, quantity: number): Observable<any> {
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

  return this.http.post(
    'http://localhost:8080/order/addtocart',
    { dealerId: 13, createdBy: "-1", productId, quantity },
    { headers, responseType: 'text'}
  ).pipe(catchError(this.errorHandlerService.handleError));
}

原文由 Poul Kruijt 发布,翻译遵循 CC BY-SA 4.0 许可协议

要修复编译器错误,请从 post 方法调用中删除泛型类型参数。

做这个

return this.http.post('example', postBody, {
  responseType: 'text'
});

不是这个

return this.http.post<any>('example', postBody, {
  responseType: 'text'
});

出现错误是因为 responseType: 'textpost 方法签名不包含泛型类型参数。

请参阅下面的不同方法签名:

使用 responseType: ‘json’ (默认)

 post<T>(url: string, body: any | null, options?: {
    ...
    responseType?: 'json';
    ...
}): Observable<T>;

使用响应类型:’文本’

 post(url: string, body: any | null, options: {
    ...
    responseType: 'text';
    ...
}): Observable<string>;

请注意,泛型类型参数仅适用于类型“json”。删除它以修复错误。

原文由 Ryan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题