2017-04-17 68 views
1

我有一個angularJS應用程序,我正在慢慢轉換爲角度,所以我的計劃是將其作爲混合應用程序,直到完全完成轉換爲止。儘管如此,我無法讓我的angularJS服務在我的角度服務中工作。我在這裏以下步驟:https://angular.io/docs/ts/latest/guide/upgrade.html#!#making-angularjs-dependencies-injectable-to-angular在角度服務中使用angularJS服務

我有我的JavaScript angularJS服務:

"use strict"; 

export class DAL { 
    get($q, $filter, $http, $log, IsoStringToDate, UnitConversion, $cookies, $uibModal, Utilities) { 
     ... functions that do stuff ... 
    } 
} 

(function() { 

    var dal = function ($q, $filter, $http, $log, IsoStringToDate, UnitConversion, $cookies, $uibModal, Utilities) { 
     var dalInst = new DAL(); 
     return dalInst.get($q, $filter, $http, $log, IsoStringToDate, UnitConversion, $cookies, $uibModal, Utilities); 
    }; 

    angular 
     .module('myWebApp') 
     .factory('DAL', ['$q', '$filter', '$http', '$log','IsoStringToDate','UnitConversion','$cookies','$uibModal','Utilities', dal]); 

}()); 

我有我的AJS升級-providers.ts:

/// <reference path="./ajs-services/index.d.ts" /> 
import { DAL } from '../../app/scripts/factory/dal'; 

export function dalServiceFactory(i: any) { 
    return i.get('DAL'); 
} 

export const dalServiceProvider = { 
    provide: DAL, 
    useFactory: dalServiceFactory, 
    deps: ['$injector'] 
}; 

但當我只是嘗試使用webpack構建項目我得到這個錯誤: 「TS2307:找不到模塊'../../app/scripts/factory/dal' 如何使用我的JavaScript模塊獲取打字稿文件?

更新:對於任何嘗試獲取混合應用程序時出現此問題的人:此方法在嘗試在Angular組件/服務中使用angularJS組件/服務時不起作用。我結束了以下建議:Use AngularJS (Angular1) module from Angular2 project 和這裏: Inject angular 1 service into Angular 2 爲了讓我的混合應用程序工作。例如:

的Javascript代碼angularJS裏面:

angular.module('myWebApp') 
    .factory('testFactory', [function() { 
     return { 
      test: function() { 
       return 'this is a test'; 
      } 
     }; 
    }]); 

app.module.ts:

import { Injectable, Inject } from '@angular/core'; 

@Injectable() 
export class TeamService { 
    constructor(@Inject('TestService') testService: any) { 
     console.log('TestService: ', testService.test()); 
    } 
} 
+0

不要將''與模塊組合在一起。它會造成傷害。只需使用'import'和'export'。 –

+0

我原本沒有參考標記,但它與它完全相同,沒有它。 –

+0

我只是指出它不應該被使用。你能證實模塊存在於相對路徑嗎? –

回答

0

添加"allowJs": true"compilerOptions"

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { UpgradeAdapter } from '@angular/upgrade'; 

@NgModule({ 
    imports: [ 
     BrowserModule, 
    ], 
    declarations: [], 
    entryComponents: [], 
    providers: [ 
    { 
     provide: 'TestService', 
     useFactory: ($injector: any) => $injector.get('testFactory'), 
     deps: ['$injector'] 
    }] 
}) 
export class AppModule { 
    ngDoBootstrap() {} 
} 

//Upgrade any angularJS components we use from old project 

let upgrade = new UpgradeAdapter(AppModule, null); 

upgrade.upgradeNg1Provider('testFactory'); 

使用angularJS服務角服務你的財產是tsconfig。 json文件或通過命令行將--allowJs轉換爲tsc,以使TypeScript能夠導入當前項目範圍內的JavaScript依賴項。

另一種方法是簡單地重命名。 js文件。 ts。與所有的JavaScript一樣,它是有效的TypeScript。