首页 > 解决方案 > 错误:对象文字只能以角度指定已知属性

问题描述

我为这个错误而疯狂:

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。你看到外面的事故了吗?

标签: angulartypescript

解决方案


正如您的错误行所示,您正在尝试将对象分配给数组。基本上,您需要将您的品牌数据推送到品牌数组中,而不是分配它。

试试这条线

this.brands = [{brand:data['brand'], checked:'false'}];

这会将您的品牌数据设置为数组的第一个元素。但是由于您的服务方法名称是“getBrands”,您确定只有一个品牌值会从服务而不是数组返回吗?


推荐阅读