Search code examples
angulartypescriptangular-services

Using Services in non-Angular Classes


I am using Angular v7.3.5 and I want to use a Service in a non-Angular class, something like this:

foo.model.ts

import { Foo2Service } from './foo2.service';
// Definition for FooClass (a model)
export class FooClass {
    constructor(args: any) {
        // Do something with args
    }

    func1() {
        // -----> Use Foo2Service here <-------
    }
}

foo2.service.ts

export class Foo2Service {
    // Service code
    constructor(private bar: BarService) {}

    init() {
        // Code that returns something
    }
}

app.component.ts

import { FooClass } from './foo.model.ts';

export class AppComponent {
    constructor() {
        const foo = new FooClass('bar');
        console.log(foo.func1());
    }
}

Is it possible to do so? If yes, what is the best way to do it?

NOTE: I tried to use the Injector class provided by Angular but it didn't work for me. So please help.


Solution

  • Using Injector should work:

    Create the injector:

    const injector = Injector.create({ 
      providers: [ 
        { provide: Foo2Service, deps:[] },
      ]
    });
    

    For the sake of the test, let's return the string test from your init function in service:

    init() {
      return 'test';
    }
    

    for testing, in your class you would call init using the injector:

    func1() {
      let myService = injector.get(Foo2Service);
      return myService.init();
    }
    

    and finally the component calling func1:

    ngOnInit() {
      const foo = new FooClass({});
      console.log(foo.func1()) // prints 'test'
    }
    

    DEMO