我有以下问题:
export class FloorManagerComponent implements OnInit
{
public meta = {
list: [],
building: Building,
loading: true,
};
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private buildingService: BuildingService
)
{;}
public async ngOnInit()
{
let params = await this.activatedRoute.params.first().toPromise();
this.meta.building = await this.buildingService // line 42: ERROR
.getBuilding(params['buildingId']) // line 42: ERROR
.toPromise(); // line 42: ERROR
}
...
}
我在编译期间遇到以下错误:
[at-loader] ./src/pages/floor/manager/floorManager.component.ts:42:9 TS2322:Type' Building'不能分配类型' typeof Building'。物业'原型'在' Building'。
中缺少类型
我被困在这里 - 任何想法?
以下是使用过的类的主体:
export class Building {
constructor(
public id: number,
public name: string,
public image_url: string,
) {}
...
}
export class BuildingService {
public getBuilding(buildingId: number)
{
return this.http.get(Url.api('buildings/' + buildingId))
.map( (response) => {
return Obj.cast(response, Building);
} );
}
...
}
export class Obj {
/**
* This method allow to cast json (and not only) obiects to given type including methods
* CAUTION: Constructor of 'type' T of object obj is never call during casting
* Example usage:
*
* let space: Space = this.cast(spaceFromJson,Space);
*
* (we use type: { new(...args): T} tp creeate fat arrow functions in prototpye... https://stackoverflow.com/a/32186367/860099)
*
* @param obj object (from json) that has only fields and no methods
* @param type desired type
* @returns {any} object that hava fields from obj and methods from type
*/
public static cast<T>(obj, type: { new(...args): T} ): T
{
obj.__proto__ = type.prototype;
return obj;
}
...
}
答案 0 :(得分:1)
我找到了解决方案:
public meta = {
list: [],
building: null as Building,
loading: true,
};
因此我们应该将building: Building
更改为building: null as Building
。因为我们在meta
字段定义中使用“对象表示法”,所以错误是我在子字段building
上使用“非对象表示法”(在“对象表示法”中:
从类型改变含义价值定义)。