首页 > 解决方案 > 如何在 Angular 的延迟加载模块中添加第三方服务?TranslateService(@ngx-translate) 和 OverlayModule 的示例

问题描述

Angular 示例应用程序中有“Minko Gechev”路由级代码拆分的分支,带有翻译和覆盖注入。

import { Component, OnInit, Injectable } from '@angular/core';
import { CookieService } from "ngx-cookie-service";
import { ComponentType, Overlay, OverlayConfig } from "@angular/cdk/overlay";

import { TranslateService } from "@ngx-translate/core";

@Injectable({
  providedIn: 'root'
})
export class OverlayService {

  constructor(public overlay: Overlay) {}
}


@Component({
  selector: 'app-nyan',
  template: '<img src="/assets/nyan.png">',
  styleUrls: ['./nyan.component.css']
})
export class NyanComponent implements OnInit {

  constructor(
    private cookieService:CookieService,
    private translateService:TranslateService,
    //private overlayService: OverlayService
  ){
     // No provider for Overlay! trouble 
    //  const overlayRef = this.overlayService.overlay.create();
    //  //touch overlay
    //  console.log(overlayRef);

  }


  ngOnInit(): void {
    // it was same trouble for cookieService but it's gone
     const lang=this.cookieService.get('lang')||'en';
     //touch cookieService
     console.log(lang);

    this.translateService.setDefaultLang('en');
    this.translateService.use(lang);
    // NullInjectorError: No provider for TranslateStore! patch from https://gitmemory.com/issue/ngx-translate/core/883/532257699
    // does not work.
    this.translateService.store.onLangChange.subscribe((lang) => this.translateService.use(lang));

  }

}

我得到的错误是:

“错误:未捕获(承诺中):NullInjectorError:StaticInjectorError(AppModule)[TranslateService -> TranslateStore]:在惰性模块中

或者

“错误错误:未捕获(承诺中):NullInjectorError:StaticInjectorError(AppModule)[InjectionToken cdk-connected-overlay-scroll-strategy -> Overlay]:StaticInjectorError(平台:核心)[InjectionToken cdk-connected-overlay-scroll-strategy - > Overlay]: NullInjectorError: No provider for Overlay!”

对于“未注释的叠加组件”版本。

这是一个堆栈闪电战

标签: angularlazy-loading

解决方案


TranslateService在惰性模块中使用,您应该首先添加AppModuleimports: [TranslateModule.forRoot(), HttpClientModule]

使用 forRoot 将在您的应用程序级别上注入 TraslateService 作为单例。

为了在您的 NyanModule 提供程序中使用 Overlay,您OverlayService应该删除providedIn: 'root';并添加 OverlayService:

 providers:[
    CookieService,
    OverlayService
  ]

因为要使用在你的惰性模块中导入的 OverlayModule,这个服务应该是这个模块的一部分。


推荐阅读