Angular联调遇NG0900错误:需正确提取响应中的产品数组
解决Angular NG0900错误:无法diff对象的问题
问题根源
你遇到的NG0900错误,本质是你把API返回的整个响应对象赋值给了数组类型的products变量,而Angular的*ngFor(或DefaultIterableDiffer)只能遍历数组/可迭代对象,无法处理普通对象。
当前你的getAll方法仅声明了返回Response["response"]类型,但实际HTTP请求返回的是包含httpCode、message、response的完整响应对象,并没有提取出真正的产品数组。
修复步骤
1. 定义完整的API响应类型(可选但推荐)
在product.service.ts中先明确API响应的TypeScript结构,避免类型混淆:
// 匹配API返回的完整结构 interface ApiResponse { httpCode: number; message: string; response: Product[]; }
2. 修改getAll方法,提取产品数组
使用RxJS的map操作符,从完整响应中取出response字段的数组:
import { map } from 'rxjs/operators'; // ... public getAll(): Observable<Product[]> { return this.http.get<ApiResponse>(this.productsUrl).pipe( map(apiResponse => apiResponse.response) // 仅返回产品数组部分 ); }
3. 确保组件变量类型正确
在catalog.component.ts中确认products变量初始化为空数组,避免undefined引发的额外问题:
products: Product[] = [];
额外检查点
- 模板中必须用
*ngFor="let product of products"遍历数组,不能误用对象 - 如果
getProductByNameLike接口的响应结构和getAll一致,需要做同样的修改,避免搜索功能出现相同错误
内容的提问来源于stack exchange,提问作者GiacominiV
相关产品推荐
相关产品推荐

