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

rah*_*gar 18 javascript typescript angular

我试图向Spring rest API发出http请求.. API返回一个字符串值("成功"或"失败")...但我不知道如何在调用API时将响应类型设置为字符串值. .其投掷的错误作为后端返回代码200,体为:[对象的对象]

我的角度代码如下,

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

错误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.');
  };

}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激...在此先感谢..

oza*_*mut 34

要摆脱错误:

类型“” text”不能分配给类型““ json””。

使用

responseType:'text'为'json'

import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
 return this.http
        .post<string>(
            this.baseUrl + '/Tickets/getTicket',
            JSON.stringify(value),
        { headers, responseType: 'text' as 'json' }
        )
        .map(res => {
            return res;
        })
        .catch(this.handleError);
Run Code Online (Sandbox Code Playgroud)

  • 我找不到“text”作为“json”在这里做什么。您能否添加该结构的名称,或者更好地解释该部分? (10认同)
  • 实际上,“responseType”只允许“json”值。Typescript 知道这一点。因此,将“text”写为“json”意味着“我给了你‘text’值,但为了进行类型检查,请考虑我给了你‘json’”。所以打字稿不会抱怨。这只允许您对打字稿“撒谎”。 (3认同)
  • 不确定“text”作为“json”的作用,但它不是一个干净的解决方案,如下所述:https://github.com/angular/angular/issues/18672#issuecomment-455435341 (2认同)
  • @MichaelWestcott 这不是我评论的重点,但你是对的。我只是在解释“text”作为“json”的含义,正如之前的评论所询问的那样。 (2认同)

Pie*_*Duc 30

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

相反,您应该将选项设置responseTypetext:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 它的编译错误... [ts]类型'{responseType:"text"的参数; ''不能赋值给'{headers?:HttpHeaders |'类型的参数 {[header:string]:string | 串[]; }; 观察?:"身体"; params?:Ht ......'.属性"responseType"的类型不兼容.类型'"text"'不能分配给''json''. (11认同)
  • @rahulshalgar如果删除泛型类型注释怎么办?我认为没有理由不这样做 (2认同)

Rya*_*yan 23

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

Angular 不需要这个泛型类型参数,因为当responseType 为“text”时,它应该始终返回一个字符串。

做这个

return this.http.post('example', postBody, {
  responseType: 'text'
});
Run Code Online (Sandbox Code Playgroud)

不是这个

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

出现错误的原因是post方法签名不包含泛型类型参数responseType: 'text

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

响应类型:'json'(默认)

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

响应类型:'文本'

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

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


Abd*_*zad 9

使用如下:

yourFunc(input: any):Observable<string> {
 var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
 const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
 return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json'  });
}
Run Code Online (Sandbox Code Playgroud)


Ami*_*ohn 9

对我来说这种方法有效。就像requestOptions 一样作为对象

 returnObservable(): Observable<any> {
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    const requestOptions: Object = {
      headers: headers,
      responseType: 'text'
    }
    return this.http.get<any>(this.streamURL , requestOptions);
 }
Run Code Online (Sandbox Code Playgroud)


Saa*_*udi 7

在您的后端,您应该添加:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)
Run Code Online (Sandbox Code Playgroud)

在前端(服务):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}
Run Code Online (Sandbox Code Playgroud)