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.

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 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;

My module

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!

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Jwqq
  • 997
  • 4
  • 14
  • 22

1 Answers1

9

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

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

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

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

Reactgular
  • 52,335
  • 19
  • 158
  • 208