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)
Pie*_*Duc 30
您不应该使用这些标头,标头确定您要发送的类型,并且您显然正在发送一个对象,即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));
}
Run Code Online (Sandbox Code Playgroud)
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”。删除它以修复错误。
使用如下:
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)
对我来说这种方法有效。就像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)
在您的后端,您应该添加:
@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)