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

uyhoqukh  于 2023-05-30  发布在  TypeScript
关注(0)|答案(9)|浏览(153)

我尝试向Spring REST API发出HTTP请求。API返回一个字符串值(“success”或“fail”)...但是我不知道如何在调用API时将响应类型设置为字符串值..其抛出错误,因为Backend返回代码200,body为:[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));
    }
}

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

}
dfddblmv

dfddblmv1#

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

hjzp0vay2#

要消 debugging 误,请执行以下操作:
类型“text”不能分配给类型“json”。
阅读Angular HTTP指南并使用
responseType:'text'作为const

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

pjngdqdw3#

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

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

前端(服务):

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

ovfsdjhp4#

使用如下:

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

pgccezyw5#

要修复编译器错误,请从post方法调用中删除泛型类型参数。
Angular不需要这个泛型类型参数,因为当responseType是“text”时,它应该总是返回一个字符串。

这样做

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

不是这个

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

出现错误是因为responseType: 'text时,post方法签名不包含泛型类型参数。
请参阅下面的不同方法签名:

使用responseType:'json'(默认值)

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

**使用responseType:联系我们

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

请注意,泛型类型参数仅存在于类型'json'中。删除它以修复错误。

xoefb8l8

xoefb8l86#

对我来说,这种方式奏效了。LikerequestOptions作为object

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

ldfqzlk87#

HttpClient的默认假设是'json' responseType。如果你想把它改成'text',你应该这样做:

public signIn(dto: UserCredentialsDto): Promise<string> {
    return this.http.post<string>(
      `${this.url}/userCredentials/signIn`, dto, { responseType: 'text' as 'json'}).toPromise();
  }
f5emj3cl

f5emj3cl8#

默认情况下,angular返回responseType为Json,但我们可以根据您的需求配置以下类型。

responseType: 'arraybuffer'|'blob'|'json'|'text'

例如:

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

wb1gzix09#

你有没有试过不设置responseType,而只是类型转换响应?
这就是我的工作:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');

  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

相关问题