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

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

问题描述

我正在尝试在我的angular 1.5/4混合应用程序中将旧的angular 1.5服务注入我的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

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天全站免登陆