簡體   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