angular - 错误:对象文字只能以角度指定已知属性
问题描述
我为这个错误而疯狂:
Object literal may only specify known properties, and 'brand' does not exist in type 'BrandCB[]'.
我不知道发生了什么事。如何解决这个问题?这是代码: gallery.component.ts
import { CarsService } from '../services/cars.service';
import { Car } from './../models/car';
import { Component, OnInit } from '@angular/core';
import { BrandCB } from '../models/brandCB';
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {
cars:Car[];
brands:BrandCB[];
selectedBrand:string;
observableCars;
observableBrands;
constructor(public carsService: CarsService) {
}
ngOnInit() {
this.getCars('all');
this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
this.brands = {brand:data['brand'], checked:'false'}; //this is the error row
console.table(data);
});
}
onOptionsSelected(event: { target: { filter: any; }; }){
this.getCars(this.selectedBrand)
}
getCars(filter){
this.observableCars = this.carsService.getCars().subscribe(data => {
if(filter!="all"){
this.cars = data.filter( car => car.brand == this.selectedBrand);
}else{
this.cars = data;
}
});
}
a(event){
let name = event.target.name;
let checked = event.target.checked;
if(name=='all'){
if(checked==true){
//uncheck tutti gli altri
}
} else {
// filtra in base alle caselle checked
// crea un array di checked items
}
}
ngOnDestroy(){
this.observableCars.unsubscribe();
this.observableBrands.unsubscribe();
}
}
品牌CB.ts
export class BrandCB {
brand:any;
checked:boolean;
}
StackOverflow 告诉我,我的帖子主要是代码,我应该写点别的,所以我在做,bla bla bla 和更多 bla bla bla。你看到外面的事故了吗?
解决方案
正如您的错误行所示,您正在尝试将对象分配给数组。基本上,您需要将您的品牌数据推送到品牌数组中,而不是分配它。
试试这条线
this.brands = [{brand:data['brand'], checked:'false'}];
这会将您的品牌数据设置为数组的第一个元素。但是由于您的服务方法名称是“getBrands”,您确定只有一个品牌值会从服务而不是数组返回吗?
推荐阅读
- python - 尝试在 Python 中匹配 Excel PERCENTRANK 公式
- php - Biiling 表单完成后,支付网关之前的 WooCommerce Hook
- python - 如何在每次绘图迭代中保持 seaborn xtick 标签相同?
- android - Exoplayer 使用 ContentResolver#openFileDescriptor(Uri, String) 设置 mediaSource,而不是 Uri.parse(MediaStore.Audio.Media.DATA)
- openshift - 如何获取使用 OC cli 创建 Openshift 项目的用户?
- amazon-web-services - 技能执行期间亚马逊 Echo 设备的唯一标识
- r - 如何使 R 中的全局变量对从 R 中调用的 C 函数可见?
- ruby-on-rails - 映射关联不执行 after_destroy
- numpy - Sympy 名称 Heaviside 未在lambdifygenerated 中定义
- java - Unirest POST 调用模拟 - 空指针异常