簡體   English   中英

打字稿 await toPromise 類型轉換錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM