简体   繁体   中英

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. I can't figure out how to inject custom services. Angular services and 3rd party services work fine. The services I need to inject are still vanilla JS services. In the example below I need to inject reportService.

The error I get is getReportById is not a function.

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. 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.

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.

Instead, it should be

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

It's a typo.

You defined a report s Service

.factory('reportsService')

But injected a different one

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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