[英]Typescript await toPromise type casting error
我有以下问题:
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:类型“Building”不可分配给类型“typeof 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;
}
...
}
我找到了解决方案:
public meta = {
list: [],
building: null as Building,
loading: true,
};
所以我们应该将building: Building
改为building: null as Building
。 因为我们在meta
字段定义中使用“对象符号”,错误是我在子字段building
使用了“非对象符号”(在“对象符号”中:
将含义从类型更改为值定义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.