我正在研究一个庞大的整体式AngularJS应用程序,并且想要添加一个Angular(如在Angular 4中)组件。不幸的是,AngularJS项目的构建系统在很大程度上是固定的,我唯一能做的就是调整项目的index.html
,例如,添加额外的<script>
标签来加载我的Angular代码。现在我的问题是如何访问AngularJS的全球angular
变量在我的角度项目的打字稿文件降级我的角度成分,使其接触到AngularJS,没有增加整个AngularJS库作为一个依赖于我的角项目,因为它是在已经捆绑AngularJS项目的加载的index.html
的JS文件。如何在Angular和TypeScript中访问AngularJS的全局`angular`变量?
说明情况多一点详细:我跟着upgrade guide从角引导的AngularJS应用程序,就像这样:
// src/app/app.module.ts of the Angular project
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { UpgradeModule } from '@angular/upgrade/static';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
UpgradeModule
],
providers: [],
})
export class AppModule {
constructor(private upgrade: UpgradeModule) { }
ngDoBootstrap() {
// Bootstrap AngularJS app
this.upgrade.bootstrap(document.documentElement, ['my-angularjs-app']);
}
}
的文件src/main.ts
和src/app/app.component.ts
不变相比默认$ ng new my-app
项目。现在,我运行$ ng build --prod
来生成生产就绪的JavaScript文件,我可以在上面提到的AngularJS项目的index.html
中包含这些文件。 (具体来说,AngularJS文件是之后的加载器。)
现在我想让AppComponent
可供AngularJS使用。 This section of the guide建议我以下行添加到上面app.module.ts
:
import { downgradeComponent } from '@angular/upgrade/static';
angular.module('my-angularjs-app')
.directive(
'my-ng2-component',
downgradeComponent({ component: AppComponent }) as angular.IDirectiveFactory
);
然而,angular
变量显然是不可用,打字稿编译器抱怨了一番。我该如何改变它?我试过下面的事情无济于事:
- 添加一行
declare var angular: any
或线let angular = window.angular
。在添加上面的降级代码时,会导致Cannot find namespace 'angular'
。 - 作为依赖添加
@types/angular
到我的角项目,并添加一行import * as angular from 'angular'
。 (这将在降级代码时导致Module not found: Error: Can't resolve 'angular'
。) - 赞2),但添加一行
/// <reference path="../../node_modules/@types/angular/index.d.ts" />
到文件 - 像2的顶部),但添加一行
/// <reference types="angular" />
到该文件的顶部。
3)和4)导致以下错误消息:
'角' 指的是一个全球UMD,但目前的文件是一个模块。 请考虑添加一个导入。
后者似乎涉及到以下两个问题在GitHub上:
是否有实际工作什么办法?不幸的是,这个升级指南非常模糊。