繁体   English   中英

使用JavaScript和TypeScript进行Angular 1依赖注入

[英]Angular 1 dependancy injection with JavaScript and TypeScript

我试图弄清楚如何在现有的Angular 1.5应用程序中使用TypeScript。 我不知道如何注入自定义服务。 Angular服务和第三方服务可以正常工作。 我需要注入的服务仍然是原始JS服务。 在下面的示例中,我需要注入reportService。

我得到的错误是getReportById不是函数。

class ReportController implements IReportController {

    static $inject = ['$stateParams', 'reportService'];


    constructor(private $stateParams: angular.ui.IStateParamsService, private reportService) {

        this.getReport($stateParams.id);
    }

    getReport(id: number): object {
        reportService.getReportById(id)
            .then(function(res) {
                console.log(res)
            });
    }

}

这是服务。

angular.module('reportsServiceModule', [])
    .factory('reportsService', [
        '$http',
        reportsService
    ]);

function reportsService(
        $http
) {

    'use strict';

    var service = {};

    service.getReportById = function(reportID) {
        return 'A promise';
    };

    return service;
}

AngularJS中JS和TS开发之间的唯一真正区别是可以键入单位。 除了类型安全之外,这什么都不会影响。

在这里

interface IReportService {
 getReportById: (someType) => string;
}

...
constructor(
  private $stateParams: angular.ui.IStateParamsService,
  private reportService: IReportService
) {
...

依赖注入没有问题。 如果您在Angular中遇到DI问题,则从进样器得到错误。

真正的问题是没有使用严格模式。 使用use strict语句或alwaysStrict TS选项时 ,错误将显示真正的错误-在getReport方法中未定义reportService变量。

相反,它应该是

getReport(id: number): object {
    this.reportService.getReportById(id)
    ...

这是一个错字。

您定义了报告服务

.factory('reportsService')

但是注入了另一个

静态$ inject = ['$ stateParams','reportService'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM