在angular / angularjs混合应用程序中使用downgradeModule和down
使用角度5.0,升级模块现在可以选择使用downgradeModule,它在角度区域之外运行
angularjs.在试验这个时,我遇到了使用downgradeInjectable的问题.
我收到错误: 未捕获错误:在引导Angular模块之前尝试获取Angular注入器. 角度js中的自举角度很好 import 'zone.js/dist/zone.js'; import * as angular from 'angular'; /** * Angular bootstrapping */ import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { decorateModuleRef } from 'src/environment'; import { AppModule } from 'src/app/app.module'; import { downgradeModule } from '@angular/upgrade/static'; export const bootstrapFn = ( extraProviders ) => { const platformRef = platformBrowserDynamic( extraProviders ); return platformRef .bootstrapModule( AppModule ) .then( decorateModuleRef ); }; angular.module( 'app.bootstrap',[ downgradeModule( bootstrapFn ),] ); 然而… 由于bootladpping是在angularjs初始化之后发生的,因此我不能再使降级注射工作. 服务被降级 import { Injectable,Inject,OnInit } from '@angular/core'; @Injectable() export class MobileService implements OnInit{ constructor( @Inject( 'angularjsDependency1' ) public angularjsDependency1 : any,@Inject( 'angularjsDependency2' ) public angularjsDependency2 : any,) {} } 降级注射尝试 import * as angular from 'angular'; import { downgradeInjectable } from '@angular/upgrade/static'; import { MyService } from 'src/services/myService/myService'; export const myServiceDowngraded = angular.module( 'services.mobileService',[ angularjsDependency1,angularjsDependency2,] ) .factory( 'mobileService',downgradeInjectable( MyService ),).name; 当“downgradeInjectable(MyService)运行时,角度注入器尚未可用,因为角度尚未被引导.因此错误: 未捕获错误:在引导Angular模块之前尝试获取Angular注入器. 有谁知道如何解决这个问题?
注意:下面的答案遵循将angular 1.x称为angularjs而将所有angular 2版本称为简单角度的约定.
扩展JGoodgive上面的答案,基本上,如果你正在使用downgradeModule,那么当需要渲染第一个角度分量时,角度模块会被angularjs懒洋洋地引导.在此之前,由于角度模块未初始化,如果使用downgradeInjectable访问angularjs中的任何角度服务,则这些服务也不可用. 解决方法是尽早强制启动角度模块.为此,需要一个简单的组件: import {Component} from '@angular/core'; @Component({ selector: 'service-bootstrap' template: '' }) export class ServiceBootstrapComponent {} 该组件不做任何事情.现在,我们在顶级角度模块中声明此组件. @NgModule({ // ...providers,imports etc. declarations: [ // ... existing declarations ServiceBootstrapComponent ],entryComponents: [ // ... existing entry components ServiceBootstrapComponent ] }) export class MyAngularModule {} 接下来,我们还需要将此组件的降级版本添加到angularjs模块. (我把它添加到了我的顶级angularjs模块) angular.module('MyAngularJSModule',[ // ...existing imports ]) .directive( 'serviceBootstrap',downgradeComponent({ component: ServiceBootstrapComponent }) as angular.IDirectiveFactory ) 最后,我们在index.html中引入了这个组件. <body> <service-bootstrap></service-bootstrap> <!-- existing body contents --> </body> 当angularjs在标记中找到该组件时,它需要初始化角度模块以便能够呈现该组件.这样做的预期副作用是提供者等也被初始化并且可以与downgradeInjectable一起使用,这可以正常使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |