3

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.

2
  • Where is this bar instance coming from? (I am referring to code new FooClass(bar);) Commented Mar 27, 2019 at 20:21
  • @Igor Oh, sorry! It was intended to be a string or an object. Fixed. Commented Mar 28, 2019 at 15:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

OK, now I know what I was doing wrong... Actually I had already did this, but not in 'Foo2Service'... Thanks, by the way...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.