我读了Angular 2 upgrade guide并成功引导了一个混合应用程序(ng1作为基本代码,现在逐步将组件和服务重写为ng2)。
现在我不明白的是我如何使用第三方ng1模块,让angular2将它们注入我的HeaderComponent?
我刚看到升级提供程序和组件的示例,但我认为我仍然对angular2中的模块概念感到困惑,所以我不知道如何升级 ng1模块。有人可以请赐教吗?
upgrade_adapter.ts
import {AppModule} from './app.module';
import {UpgradeAdapter} from '@angular/upgrade';
export const upgradeAdapter = new UpgradeAdapter(AppModule);
app.module.ts
// imports...
@NgModule({
imports: [
BrowserModule,
HttpModule
],
declarations: [
HeaderComponent
],
providers: [ MyService ]
})
export class AppModule { }
index.ts
import { upgradeAdapter } from './upgrade_adapter';
// more imports...
angular.module(MODULE_NAME, [
//...
])
// HeaderComponent uses a ng1 3rd party module, how to use that module in that component
.component('header', upgradeAdapter.downgradeNg2Component(HeaderComponent))
// adding some ng1 components...
.factory('myService', upgradeAdapter.downgradeNg2Provider(MyService));
// bootstrap the application
angular.element(document).ready(function () {
upgradeAdapter.bootstrap(document.body, [MODULE_NAME]);
});
修改
第三方模块是用JS编写的。
lib / angular-modules / communication / index.js
var communicationModule = angular.module('communication', [])
.factory('communication', require('./communication.factory'));
module.exports = communicationModule.name;
答案 0 :(得分:1)
所以我遇到了类似的问题,基本上我想在子模块中声明ng1组件。我发现这样做的唯一方法是使用一个虚拟类来构建upgradeAdapter,然后在调用bootstrap方法之前将其切换出来。您需要为Angular 2创建新模块并在其中声明ng1组件。
希望这有所帮助,花了我很多时间来锻炼。
<强> upgrade_adapter.ts 强>
import {UpgradeAdapter} from '@angular/upgrade';
import { NgModule, forwardRef } from '@angular/core';
export const upgradeAdapter = new UpgradeAdapter(forwardRef(() => DummyClass)
@NgModule({})
export class DummyClass { }
<强> app.module.ts 强>
import { Ng1Module } from 'ng1.module';
// imports...
@NgModule({
imports: [
BrowserModule,
HttpModule,
Ng1Module
],
declarations: [
HeaderComponent
],
providers: [ MyService ]
})
export class AppModule { }
<强> ng1.module.ts 强>
import { upgradeAdapter } from './upgrade-adapter'
@NgModule( {
declarations:[upgradeAdapter.upgradeNg1Component('ng1Component'),]
})
export class Ng1Module {}
<强> index.ts 强>
import { upgradeAdapter } from './upgrade-adapter'
import { AppModule} from './app.module'
/** codes **/
angular.element(document).ready(function () {
upgradeAdapter['ng2AppModule'] = AppModule;
upgradeAdapter.bootstrap(document.body, ['app']);
});