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

23 浏览
0 Comments

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

我正在尝试向Spring REST API发起http请求... API返回一个字符串值("success"或"fail")... 但是我不知道在调用API时如何设置响应类型为字符串值...报错为后端返回代码200,主体为:[object Object]

我的Angular代码如下,

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 {
    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('http://localhost:8080/order/addtocart', 
              { dealerId: 13, createdBy: "-1", productId: productId, quantity: quantity}, 
              {headers: headers})
              .pipe(catchError(this.errorHandlerService.handleError));
    }
}

error-handler.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) {
      // 发生客户端或网络错误。相应地处理。
      console.error('发生错误:', error.error.message);
    } else {
      // 后端返回了一个失败的响应代码。
      // 响应主体可能包含出错的线索,
      console.error(
        `后端返回代码 ${error.status}, ` +
        `body为:${error.error}`);
    }
    // 返回一个可观察的用户可见的错误消息
    return throwError(
      '发生了一些错误,请稍后重试。');
  };
}

0