在我的情况下如何将服务注入模块? [英] How to inject an service into module in my case?

查看:26
本文介绍了在我的情况下如何将服务注入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将旧的 angular 1.5 服务注入到我的 angular 1.5/4 混合应用程序中的 angular 4 模块中.

I am trying to inject an old angular 1.5 service into my angular 4 module in my angular 1.5/4 hybrid app.

MyService 使用静态方法,因为如果我将其设为公开,则无法使用new MyService() 因为 MyService 需要一个我不知道如何提供的参数.

The MyService uses a static method because if I make it a public, I have no way to initial it with new MyService() because MyService expects a param that I don't know how to provide.

我的班级 (my-service.class.ts)

My 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 {}

基本上我不确定如何将我的旧服务注入静态方法.有帮助吗?非常感谢!

Basically I am not sure how to inejct my old service into a static method. Any helps? Thanks a lot!

推荐答案

如果您只需要在加载模块时运行代码.您将该代码放在模块的构造函数中.

If you need to run code only when a module is loaded. You place that code inside the constructor of the module.

您必须将您的服务注入到 MyModule

You have to inject your service into the constructor of the MyModule

export class MyModule {
     constructor(MyService service) {
         console.log(service.getMyUrl());
     }
}

您还必须从服务中删除 static.不要对可注入服务使用静态方法.

You also have to remove static from the service. Don't use static methods with injectable services.

这篇关于在我的情况下如何将服务注入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆