angular - 如何在 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!”
对于“未注释的叠加组件”版本。
这是一个堆栈闪电战。
解决方案
要TranslateService
在惰性模块中使用,您应该首先添加AppModule
:
imports: [TranslateModule.forRoot(), HttpClientModule]
使用 forRoot 将在您的应用程序级别上注入 TraslateService 作为单例。
为了在您的 NyanModule 提供程序中使用 Overlay,您OverlayService
应该删除providedIn: 'root';
并添加 OverlayService:
providers:[
CookieService,
OverlayService
]
因为要使用在你的惰性模块中导入的 OverlayModule,这个服务应该是这个模块的一部分。
推荐阅读
- python - 如何从 python 脚本在 azure devops 管道中生成合理的错误消息
- javascript - 如何在点击 Javascript 时在 index.html 中加载另一个 html
- swift - 使用 MKLocalSearch/MapKit 查找附近的餐馆?
- node.js - 在从 typescript 编译的代码中导入 PrismaClient 时出错 [SyntaxError: Named export 'PrismaClient' not found]
- python - cv2 python 颜色无法正常工作(绘图)
- firebase - 如何访问firestore文档中的集合并将其作为列表分配给模型中的飞镖列表?
- python - 使用 Psycopg2 从 PostgreSQL 数据库获取行的正确方法是什么?
- java - 从内部联接插入信息
- typescript - 将类型转换为类型元组的实用程序类型
- itext - itext7:定位签名的矩形