在AppModule中提供Angular“ErrorHandler”导致延迟子模块路由中的“找不到模块”

时间:2018-03-06 21:40:33

标签: angular angular-cli

我有一个关于Angular是如何工作的一般性问题,目前我不知道它是否是“ng服务”中的错误或Angular的内部机制我不理解。

我的项目包含从App Component>加载的不同模块。布局组件> [其他懒人模块]

以下是该结构的摘录: app modules tree

Ant布局组件的路由:

import { RouterModule, Routes } from '@angular/router';
import { LayoutComponent } from './layout.component';
import {AuthGuard} from '../auth/guards/auth-guard';

const routes: Routes = [
  {
    path: 'app',
    component: LayoutComponent,
    canActivate: [AuthGuard],
    children: [
      { path: '', loadChildren: '../home/home.module#HomeModule' },
      { path: '', loadChildren: '../admin/admin.module#AdminModule' },
      { path: '', loadChildren: '../campaigns/campaigns.module#CampaignsModule' },
      { path: '', loadChildren: '../campaigns/campaigns.module#CampaignsModule' },
      { path: '', loadChildren: '../channels/channels.module#ChannelsModule' },
      { path: '', loadChildren: '../users/users.module#UsersModule' },
      { path: '', loadChildren: '../visualizer/visualizer.module#VisualizerModule' },
      { path: '', loadChildren: '../agency/agency.module#AgencyModule' },
      { path: '', loadChildren: '../publisher/publisher.module#PublisherModule' }
    ]
  }
];

export const LayoutRoutingModule = RouterModule.forChild(routes);

从项目开始以来,我从未遇到任何路由问题。 最近我想在AppModule级别的应用程序中集成一个ErrorHandler。

我的AppModule:

@Injectable()
class MyErrorHandler implements ErrorHandler {
  constructor(private injector: Injector) {

  }
  handleError(error: Error) {
    const angulartics2GoogleAnalytics = this.injector.get(Angulartics2GoogleAnalytics);

    if (environment.production === false) {
      console.error(error);
    }

    angulartics2GoogleAnalytics.exceptionTrack({fatal: false, description: error.name + ' ' + error.stack});
  }
}


export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './vendors/lang/', '.json');
}
declare const require;
export function translationsFactory(localData: string) {
  localData = localData || 'en'; // default to english if no locale
  return require(`raw-loader!../locale/messages.${localData}.xlf`);
}
@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    AuthModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    LayoutModule,
    ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }),
    ServiceWorkerModule.register('/firebase-messaging-sw.js'),
    SharedMaterialModule,
    PopoverModule.forRoot(),
    Angulartics2Module.forRoot([Angulartics2GoogleAnalytics], {
      developerMode: false,//!environment.production,
      pageTracking: {
        clearQueryParams: false,
        clearIds: true,
        idsRegExp: new RegExp('^[0-9a-fA-F]{24}$')
      }
    }),
    MomentModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    CookieModule.forRoot(),
    BsDropdownModule.forRoot(),
    SharedModule,
  ],
  declarations: [
    AppComponent,
    LayoutComponent,
    PreloaderDirective,
    AppHeaderComponent,
    AppSidenavComponent,
    ToggleOffcanvasNavDirective,
    AutoCloseMobileNavDirective,
    AppSidenavMenuComponent,
    AccordionNavDirective,
    AppendSubmenuIconDirective,
    HighlightActiveItemsDirective,
    AppCustomizerComponent,
    ToggleQuickviewDirective,
    AppFooterComponent,
    AppSearchOverlayComponent,
    SearchOverlayDirective,
    OpenSearchOverlaylDirective,
  ],
  exports: [
    TranslateModule,
    CookieModule
  ],
  providers: [
    {provide: LocationStrategy, useClass: HashLocationStrategy},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'},
    {provide: MISSING_TRANSLATION_STRATEGY, useValue: MissingTranslationStrategy.Error},
    {provide: LOCALE_ID, useValue: 'fr'},
    {
      provide: TRANSLATIONS,
      useFactory: translationsFactory,
      deps: [LOCALE_ID]
    },
    AuthService,
    AlertService,
    MessagingService,
    TourGuideService,
    I18n,
    /*
    {provide: ErrorHandler, useClass: MyErrorHandler}
    */
  ],
  bootstrap: [AppComponent]
})

export class AppModule {
  constructor(public appRef: ApplicationRef) {}
  hmrOnInit(store) {
  }
  hmrOnDestroy(store) {
    const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement);
    // recreate elements
    store.disposeOldHosts = createNewHosts(cmpLocation);
    // remove styles
    removeNgStyles();
  }
  hmrAfterDestroy(store) {
    // display new elements
    store.disposeOldHosts();
    delete store.disposeOldHosts;
  }
}

如果我在没有切断ng服务过程的情况下提供服务,一切正常,但是当我剪切服务并重新启动它时,编译工作,但是在加载页面时我有错误:

"Error: Uncaught (in promise): Error: Cannot find module '../home/home.module'."

删除此单行足以解决问题:

{provide: ErrorHandler, useClass: MyErrorHandler}

有人可以在这个不起眼的问题上启发我吗?我在很多Google搜索或Stack Overflow中找不到任何类似的问题

这是第一个与Angular相关的问题,我近三年没有找到解决方案,祝贺Angular团队!

提前感谢整个社区:)

(抱歉我的英语不好)

1 个答案:

答案 0 :(得分:0)

尝试在您的ErrorHandler类中添加“导出”:

@Injectable()
export class MyErrorHandler implements ErrorHandler {
    ...
}