我正在try 向spring rest API发出http请求..API返回一个字符串值("成功"或"失败")...但我不知道在调用API时如何将响应类型设置为字符串值..its throwing error as Backend returned code 200, body was: [object Object]

我的Angular 代码如下,

顺序服务.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("--------顺序服务.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));
    }
}

错误处理程序.服务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.');
  };

}

任何帮助都将不胜感激...提前谢谢..

推荐答案

您不应该使用这些标题,这些标题决定了您要发送的类型,而且您显然是在发送一个对象,也就是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));
}

Typescript相关问答推荐

根据第一个参数的值设置第二个参数的类型

如何在另一个if条件中添加if条件

如何传递基于TypScript中可变类型的类型?

Vue SFC中的多个脚本块共享导入的符号

路由链接不会导航到指定router-outlet 的延迟加载模块

对于合并对象中的可选属性(例如选项),类型推断可能是错误的

返回具有递归属性的泛型类型的泛型函数

如何在处理数组时缩小几个派生类实例之间的类型范围?

如何创建一家Reduxstore ?

有什么方法可以类型安全地包装import()函数吗?

如何在Typescript 中组合unions ?

ANGLE订阅要么不更新价值,要么不识别价值变化

将对象的属性转换为正确类型和位置的函数参数

当数组类型被扩展并提供标准数组时,TypeScrip不会抱怨

使用ngfor循环时,数据未绑定到表

如何使用useSearchParams保持状态

导航链接不触发自定义挂钩

仅当定义了值时才按值筛选数组

如何在TypeScript中声明逆变函数成员?

基于参数的 TS 返回类型