Angular类型错误求助:普通数组无法赋值给单元素元组类型
Angular类型错误问题解决:复制订单产品数组失败
错误信息
error TS2322: Type '{ sifra: string; naziv: string; kolicina: number; ean: string; em: string; cena: number; rabat1: number; rabat2: number; prednarocilo: number; ismail: number; }[]' is not assignable to type '[{ sifra: string; naziv: string; kolicina: number; ean: string; em: string; cena: number; rabat1: number; rabat2: number; prednarocilo: number; ismail: number; }]'. [ng] Target requires 1 element(s) but source may have fewer. [ng] [ng] 38 this.orderProducts = data.map(this.order['izdelki']);
问题根源
- 服务类型定义错误:获取单个订单的API返回的是单个
SingleOrder对象,但服务错误定义为返回Observable<SingleOrder[]>(数组类型),导致组件中数据处理逻辑完全偏离。 - 组件类型不匹配:
orderProducts被定义为SingleOrder['izdelki'][](即「产品数组的数组」),但实际需要的是单个产品数组(SingleOrder['izdelki']),类型不匹配触发TS类型检查报错。 map方法误用:data.map(this.order['izdelki'])是错误用法,map需要传入回调函数,而非直接传递数组;同时因为data被错误当作数组处理,单个订单场景下根本不需要使用map。
代码修正
1. 修正订单服务代码
将单个订单接口的返回类型从数组改为单个对象:
getSingleOrder(id: number): Observable<SingleOrder> { return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe( switchMap(token => { const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`); // 修正泛型为SingleOrder,对应单个订单对象 return this.httpClient.get<SingleOrder>(`${environment.apiUrl}customer/orders/${id}`, { headers, observe: 'response' }); }), catchError(err => { console.log(err.status); if (err.status === 400) { console.log(err.error.message); } if (err.status === 401) { this.authService.logout(); this.router.navigateByUrl('/login', { replaceUrl: true }); } return EMPTY; }), map(res => res.body) ); };
2. 修正组件代码
调整类型定义和数据赋值逻辑:
export class Izdelki { sifra: string; naziv: string; kolicina: number; ean: string; em: string; cena: number; rabat1: number; rabat2: number; prednarocilo: number; ismail: number; } @Component({ selector: 'app-order-view', templateUrl: './order-view.page.html', styleUrls: ['./order-view.page.scss'], }) export class OrderViewPage implements OnInit, OnDestroy { // 单个订单对象,加?表示可选避免初始未赋值报错 order?: SingleOrder; // 类型为单个产品数组,而非数组的数组 orderProducts: SingleOrder['izdelki'] = []; repeatOrderArr: Izdelki[] = []; private orderSubscription: Subscription; constructor( private route: ActivatedRoute, private customerService: CustomerService, ) { } ngOnInit() { this.getOrder(); } getOrder() { const id = Number(this.route.snapshot.paramMap.get('id')); this.orderSubscription = this.customerService.getSingleOrder(id).subscribe( data => { this.order = data; console.log('Order data:', this.order); // 直接取单个订单的izdelki数组 this.orderProducts = this.order.izdelki; }, error => { console.log('Error', error); }); } repeatThisPurchase() { // 扩展运算符复制数组 this.repeatOrderArr = [...this.orderProducts]; console.log(this.repeatOrderArr); } ngOnDestroy(): void{ this.orderSubscription.unsubscribe(); } }
关键解释
- 服务返回类型修正后,组件中
data变为单个SingleOrder对象,直接取izdelki属性即可拿到产品数组。 orderProducts类型调整为SingleOrder['izdelki'],与实际需要的产品数组类型完全匹配,解决TS类型不兼容问题。- 移除错误的
map调用,简化数据赋值逻辑,避免不必要的数组处理。
内容的提问来源于stack exchange,提问作者weinde
相关产品推荐
相关产品推荐

