Angular 6:如何在进行http调用时将响应类型设置为文本 [英] Angular 6: How to set response type as text while making http call

查看:485
本文介绍了Angular 6:如何在进行http调用时将响应类型设置为文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图向spring rest API发出http请求.. API返回一个字符串值(success或fail)...但我不知道如何在调用时将响应类型设置为字符串值API .. 它的抛出错误,因为Backend返回代码200,正文是:[object Object]

I trying to make http request to the spring rest API.. API returns a string value ("success" or "fail")... but I dont know how to set the response type as string value while making call to the API..its throwing error as Backend returned code 200, body was: [object Object]

我的角度代码如下所示,

My angular code is like below,

order.service.ts

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));
    }
}

error-handler.service.ts

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) {
      // 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.');
  };

}

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

Any help would be appreciated... thanks in advance..

推荐答案

您不应该使用这些标题,标题会确定您要发送的是哪种类型,并且您显然正在发送对象,表示JSON。

You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.

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

Instead you should set the option responseType to 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));
}

这篇关于Angular 6:如何在进行http调用时将响应类型设置为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆