我正在尝试将旧的 Angular 1.5 服务注入(inject)到我的 Angular 1.5/4 混合应用程序中的 Angular 4 模块中。
MyService
使用静态方法,因为如果我将其公开,我将无法使用它来初始化它
new MyService()
因为 MyService
需要一个我不知道如何提供的参数。
我的类(class)(my-service.class.ts)
import {Inject, Injectable} from '@angular/core';
@Injectable()
class MyService {
constructor(
@Inject('myOldService') private myOldService: any) {}
static getMyUrl() {
console.log(this.myOldService);
// complains
// Property 'myOldService' does not exist on type 'typeof MyService
return this.myOldService.getItemUrl();
}
}
export default MyService;
我的模块
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
...other import..
import MyService from './my-service.class';
console.log(MyService.getMyUrl())
//has error because getMyUrl has error.
@NgModule({
'imports': [
CommonModule
],
'declarations': [
MyComponent
],
'providers': [
MyService
]
})
export class MyModule {}
基本上,我不确定如何将旧服务注入(inject)静态方法。有什么帮助吗?非常感谢!
最佳答案
如果您只需要在加载模块时运行代码。您将该代码放在模块的构造函数中。
你必须将你的服务注入(inject)到 MyModule
export class MyModule {
constructor(MyService service) {
console.log(service.getMyUrl());
}
}
您还必须从服务中删除 static
。不要对可注入(inject)服务使用静态方法。
关于angular - 在我的情况下,如何将服务注入(inject)模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521960/