当我尝试从api中获取数据时,在我的angular 6项目上遇到此错误。这是我的api json文件;
{"data":
[{"category_name":"Women Ready Made","slug":null,"image_url":"education.jpg","products":
[{"productName":"Kampala
Shorts","description":"Beautiful Handwoven Kampala Shorts","imageUrl":"C:\\codes\\Tradsonline\\img\\image1.jpg","price":2500,"discount":10},{"productName":"Flowing White Agbada","description":"Flowing white agbada with beautiful design.","imageUrl":"C:\\codes\\Tradsonline\\img\\image3.jpg","price":22000,"discount":15}]},{"category_name":"Men's Ready Made","slug":null,"image_url":"education.jpg","products":[{"productName":"Ankara Jacket","description":"Ankara Jackets with pockets.","imageUrl":"C:\\codes\\Tradsonline\\img\\image2.jpg","price":5000,"discount":15},{"productName":"Women Ankara Gown","description":"Women Ankara gown with beautiful design.","imageUrl":"C:\\codes\\Tradsonline\\img\\image4.jpg","price":8000,"discount":0}]},{"category_name":"Ankara Gowns","slug":null,"image_url":"education.jpg","products":[]}]}
这是我的服务
getCategories(): Observable<Category[]> {
return this.http.get(this.base_url + 'categories')
.pipe(map(res => {
return res.data; //this is where the error happens
}));
这是我在服务上的导入
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Product } from '../models/product';
import { Category } from '../models/category';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
错误来自哪里?
答案 0 :(得分:2)
如果您没有为http.get
调用指定通用类型参数,则假定object
是传递给map
的类型。 object
没有名为data
的属性(您正在调用),因此发生了转换时间错误。
对其进行更改,以便在对http.get<T>
的调用中以通用类型约束定义返回的结构。
getCategories(): Observable<Category[]> {
return this.http.get<{data: Category[]}>(this.base_url + 'categories')
.pipe(map(res => {
return res.data; // now .data is known and is expected to contain Category[]
}));
}