作者:闹剧-豆腐渣_141 | 来源:互联网 | 2023-02-01 12:04
1> Anton..:
好吧,经过几个小时的挣扎,我终于找到了解决方案.这里是:
升级第三方服务
首先,遵循Angular的官方指南并升级第三方服务的提供商 - $translate
.像这样:
AJS升级,providers.ts
import { InjectionToken } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';
import 'angular-translate';
// Variable 'i' holds the standard AngularJS injector
export function $translateFactory(i: any) {
return i.get('$translate');
};
// There is no class representing the good old $translate service so we have
// a non-class dependency. Therefore we use an InjectionToken (Angular 4) or
// OpaqueToken (Angular 2).
export let $translate = new InjectionToken('$translate');
// Finally create the upgraded provider
export const $translateProvider = {
provide: $translate,
useFactory: $translateFactory,
deps: ['$injector']
};
有一点需要注意,$translate
服务可能依赖于其他旧的AngularJS服务,例如(在我的情况下)$translateStaticFilesLoader
或$translateMessageFormatInterpolation
.如果这也是您的情况,请务必扩展上面的代码并为这些服务创建升级的提供程序(将它们保存在同一个文件中).
确保该import
语句有效
它angular-translate
是作为节点模块安装的语句
import 'angular-translate';
如果您tsconfig.json
已设置使用,则工作正常moduleResolution: "node"
.
然后,当然,您需要确保该import
语句即使在将代码从TypeScript转换为ES5(或您使用的任何目标)并由模块加载器(在我的情况下为SystemJS)中获取之后也能正常工作.
请注意,我们导入angular-translate
脚本时没有从中获取任何内容,只是为了引起副作用.基本上,导入确保$translate
简单地执行包含所需服务的脚本并$translate
为AngularJS $注入器注册服务.
在Angular模块中注册升级的提供程序
现在确保新升级的$translate
服务提供商在其他提供商中注册MyModule
.
my.module.ts
import { NgModule } from '@angular/core';
import { MyService } from './my.service';
import { $translateProvider } from './ajs-upgraded-providers';
@NgModule({
providers: [
MyService,
$translateProvider
]
})
export class MyModule {
}
用它
最后,使用该$translate
服务MyService
.
my.service.ts
import { Injectable, Inject } from '@angular/core';
import { $translate } from './ajs-upgraded-providers';
@Injectable()
export class MyService {
// Notice the usage of InjectionToken
constructor(@Inject($translate) private $translate: any) {
}
foo() {
this.$translate('hello.world').then((translation: string) => {
console.log(translation);
});
}
}