【发布时间】:2021-10-19 03:04:26
【问题描述】:
我想从 API 获取我的数据。 API 本身在 postmap 中运行良好,如下所示:
{
"status": "Success",
"data": [
{
"title": "asus g551 vw",
"price": 500,
"image": "https://localhost:44345/images/products/origin/img1.jpg",
"count": 2
},
{
"title": "asus vivobook",
"price": 1200,
"image": "https://localhost:44345/images/products/origin/img1.jpg",
"count": 2
},
{
"title": "acer predator",
"price": 200,
"image": "https://localhost:44345/images/products/origin/img1.jpg",
"count": 1
}
]
}
但是在 Angular 中,当我调用我的 get 函数时,我从这个 Angular 代码中得到一个错误:
myservice method 'GetUserBasketDetails()' :
@Injectable({
providedIn: 'root'
})
export class OrderService {
private orderDetails : BehaviorSubject<OrderBasketDto[]> = new BehaviorSubject<OrderBasketDto[]>(null);
constructor(private _http : HttpClient) { }
_SetOrderDetails(details : OrderBasketDto[]){
this.orderDetails.next(details);
console.log(this.orderDetails)
}
_GetOrderDetails() : Observable<OrderBasketDto[]>{
return this.orderDetails;
}
GetUserBasketDetails():Observable<IResponseResult<OrderBasketDto[]>>{
return this._http.get<IResponseResult<OrderBasketDto[]>>('/basket-details');
}
}
当我在组件中调用它时:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'Front-Project';
constructor(private _accountService : AccountService,
private _orderService : OrderService) {
}
ngOnInit():void {
this._orderService.GetUserBasketDetails().subscribe(res=>{
console.log(res)
})
}
}
这是我得到的错误:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://localhost:44345/basket-details", ok: false, ...}
和
错误:SyntaxError: Unexpected token
我该如何解决这个问题?
【问题讨论】:
-
您没有从服务器得到正确的响应。复制 URL 后尝试 curl 请求。
-
即使状态码是 200 OK,响应似乎包含错误,
Unexpected token < in JSON暗示响应实际上是 HTML 字符串而不是 JSON。 -
您对映射 IResponseResult
感到满意吗?您是否尝试不映射?如果你有回应?
标签: json angular api syntax-error asp.net-core-webapi