export class FeaturedCategories {
categories: Array<{ id: number, title: string, graphic: string, categorycards: Array<{}> }>;
}
还尝试了这个:
export class FeaturedCategories {
id: number;
title: string;
graphic: string;
categorycards: Object[];
}
组件
import { Component, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { ApiService } from '../shared/services/api.service';
import { FeaturedCategories } from '../shared/models/home/featuredcategories';
@Component({
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated,
selector: 'home',
styleUrls: [ './home.component.css' ],
templateUrl: './home.component.html'
})
export class HomeComponent {
testFeaturedCategories: Array<FeaturedCategories>;
constructor(private api: ApiService) {
// we need the data synchronously for the client to set the server response
// we create another method so we have more control for testing
this.universalInit();
}
universalInit() {
console.log('universalInit...')
this.api.getFeatured()
.subscribe(categories => {
console.log('categories', categories);
this.testFeaturedCategories = categories
});
}
}
这将起作用:
testFeaturedCategories: Array<{}>;
但是,我正在尝试使用TypeScript来让我的App知道预期的模型类型。
这会导致上面的错误:
testFeaturedCategories: FeaturedCategories.categories;
如果我只是试一试:
testFeaturedCategories: FeaturedCategories;
我收到一个
type [{}] is not assignable
错误。更新
所以我注意到当我注释掉
FeaturedCategories
模型中的所有键时,错误消失了,featuredCategories: FeaturedCategories[];
将起作用。但是现在这只是一个空对象,没有键可以期望:(
export class FeaturedCategories {
// id: number;
// title: string;
// graphic: string;
// categorycards: Object[];
}
最佳答案
这对我来说很好。
export class MyComponent {
categories: FeaturedCategories[] = [{
id: 1,
title: "",
graphic: "",
categorycards: [{}]
}];
}
export class FeaturedCategories{
id: number;
title: string;
graphic: string;
categorycards: Object[];
}