async constructor functions in TypeScript?

前端 未结 8 1839
青春惊慌失措
青春惊慌失措 2020-12-13 05:43

I have some setup I want during a constructor, but it seems that is not allowed

Which means I can\'t use:

How else should I do this?

<
8条回答
  •  一向
    一向 (楼主)
    2020-12-13 06:02

    You may elect to leave the await out of the equation altogether. You can call it from the constructor if you need to. The caveat being that you need to deal with any return values in the setup/initialise function, not in the constructor.

    this works for me, using angular 1.6.3.

    import { module } from "angular";
    import * as R from "ramda";
    import cs = require("./checkListService");
    
    export class CheckListController {
    
        static $inject = ["$log", "$location", "ICheckListService"];
        checkListId: string;
    
        constructor(
            public $log: ng.ILogService,
            public $loc: ng.ILocationService,
            public checkListService: cs.ICheckListService) {
            this.initialise();
        }
    
        /**
         * initialise the controller component.
         */
        async initialise() {
            try {
                var list = await this.checkListService.loadCheckLists();
                this.checkListId = R.head(list).id.toString();
                this.$log.info(`set check list id to ${this.checkListId}`);
             } catch (error) {
                // deal with problems here.
             }
        }
    }
    
    module("app").controller("checkListController", CheckListController)
    

提交回复
热议问题