简体   繁体   English

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

[英]Angular 1 dependancy injection with JavaScript and TypeScript

I'm trying to figure out how to use TypeScript in an existing Angular 1.5 app. 我试图弄清楚如何在现有的Angular 1.5应用程序中使用TypeScript。 I can't figure out how to inject custom services. 我不知道如何注入自定义服务。 Angular services and 3rd party services work fine. Angular服务和第三方服务可以正常工作。 The services I need to inject are still vanilla JS services. 我需要注入的服务仍然是原始JS服务。 In the example below I need to inject reportService. 在下面的示例中,我需要注入reportService。

The error I get is getReportById is not a function. 我得到的错误是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)
            });
    }

}

Here is the service. 这是服务。

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

function reportsService(
        $http
) {

    'use strict';

    var service = {};

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

    return service;
}

The only real difference between JS and TS development in AngularJS is that the units can be typed. AngularJS中JS和TS开发之间的唯一真正区别是可以键入单位。 This doesn't affect anything but type safety. 除了类型安全之外,这什么都不会影响。

Here it would be 在这里

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

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

There's no problem with dependency injection. 依赖注入没有问题。 If you have DI problem in Angular, you get an error from injector. 如果您在Angular中遇到DI问题,则从进样器得到错误。

The real problem here is that strict mode isn't used. 真正的问题是没有使用严格模式。 With use strict statement or alwaysStrict TS option the error would show what's really wrong - reportService variable is not defined in getReport method. 使用use strict语句或alwaysStrict TS选项时 ,错误将显示真正的错误-在getReport方法中未定义reportService变量。

Instead, it should be 相反,它应该是

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

It's a typo. 这是一个错字。

You defined a report s Service 您定义了报告服务

.factory('reportsService') .factory('reportsService')

But injected a different one 但是注入了另一个

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

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

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