【发布时间】:2017-09-13 14:22:15
【问题描述】:
我有一个 angularJS 应用程序,我正在慢慢转换为 angular,所以我的计划是将它作为一个混合应用程序,直到我完全完成转换。不过,我无法让我的 angularJS 服务在我的 Angular 服务中工作。我按照这里的步骤操作:https://angular.io/docs/ts/latest/guide/upgrade.html#!#making-angularjs-dependencies-injectable-to-angular
我有我的 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-upgraded-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 模块获取 typescript 文件?
更新:对于在尝试使混合应用程序工作时最终出现在这里的任何人:当尝试在 Angular 组件/服务中使用 angularJS 组件/服务时,这种方法不起作用。我最终在这里遵循了建议:Use AngularJS (Angular1) module from Angular2 project 和这里: Inject angular 1 service into Angular 2 让我的混合应用程序正常工作。示例:
angularJS代码中的Javascript:
angular.module('myWebApp')
.factory('testFactory', [function() {
return {
test: function() {
return 'this is a test';
}
};
}]);
app.module.ts:
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 服务的 Angular 服务:
import { Injectable, Inject } from '@angular/core';
@Injectable()
export class TeamService {
constructor(@Inject('TestService') testService: any) {
console.log('TestService: ', testService.test());
}
}
【问题讨论】:
-
不要将
<reference path="" />与模块结合使用。会造成伤害。只需使用import和export。 -
我最初没有引用标签,但有它和没有它都是完全相同的错误。
-
我只是指出不应该使用它。您能否验证该模块是否存在于相对路径中?
-
试试
--allowJs -
--allowJs 工作!在我将它添加到我的 tsconfig.json 之后,它就构建好了。谢谢!如果您想将其作为答案,我可以将其标记为官方答案。
标签: javascript angularjs typescript