如何为控制器工厂返回类型编写接口

时间:2016-05-12 13:34:17

标签: angularjs typescript typescript1.8

我试图摆脱对任何'任何'从我的应用程序尽可能。有可能摆脱这个 - 我可以为我的控制器工厂写什么界面?

return (controller) as any;
module TsApp.Home {
    "use strict";

    export interface IBlogEntries {
        blogEntries: Common.BlogEntry[];
    }

    interface IBaHomeController {
        $scope: IBlogEntries;
        baBlogEntriesService: Common.IBlogEntries;
        $http: ng.IHttpService;
    }

    class BaHomeController {
        $scope: IBlogEntries;
        baBlogEntriesService: Common.IBlogEntries;
        $http: ng.IHttpService;

        public static factory(): IBaHomeController[] {
            const controller = (log: ng.ILogService, $scope: IBlogEntries, blogEntriesService: Common.IBlogEntries, http: ng.IHttpService
            ): IBaHomeController => {
                return new BaHomeController(log, $scope, blogEntriesService, http);
            };

            controller.$inject = ["$log", "$scope", "BaBlogEntriesService", "$http"];

            return (controller) as any; //#2
        }

        constructor(private $log: ng.ILogService, $scope: IBlogEntries, private bBaBlogEntriesService: Common.IBlogEntries,
            private http: ng.IHttpService) {
            const defer = bBaBlogEntriesService.getAsync();
            defer.then(response => {
                $scope.blogEntries = response.data;
                $log.debug("blog entries");
            });
        }
    }

    angular
        .module("Main")
        .controller("BaHomeController", BaHomeController.factory()); //#1
}

我认为"返回(控制器)为IBaHomeController [];"会工作,但我得到这个错误:

  

两种类型'(日志:ILogService,$ scope:IBlogEntries,blogEntriesService:IBlogEntries,http:IHttpService)=> ...'也不输入' IBaHomeController []'可分配给另一个。     物业'推动'缺少类型'(日志:ILogService,$ scope:IBlogEntries,blogEntriesService:IBlogEntries,http:IHttpService)=> ...'。

由于这是方法定义的返回类型,我认为它会起作用。这让我相信我需要改变方法的返回类型?

编辑:如果有一种更简单的方式来注入依赖项,那对我也有用。

1 个答案:

答案 0 :(得分:1)

它抱怨,因为工厂方法的返回类型是IBaHomeController的数组,并且您尝试返回BaHomeController的单个实例并尝试将其转换为数组。

如果你返回一个单一的实体,那就可以了。

  public static factory(): IBaHomeController {
        const controller = (log: ng.ILogService, $scope: IBlogEntries, blogEntriesService: Common.IBlogEntries, http: ng.IHttpService
        ): IBaHomeController => {
            return new BaHomeController(log, $scope, blogEntriesService, http);
        };

        controller.$inject = ["$log", "$scope", "BaBlogEntriesService", "$http"];

        return (controller) as IBaHomeController;
    }

不确定是否能解决您的目的。

希望这会有所帮助!!