在非 Angular 类 中使用服务

Using Services in non-Angular Classes

我正在使用 Angular v7.3.5,我想在非 Angular class 中使用服务,如下所示:

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());
    }
}

可以吗?如果是,最好的方法是什么?

注意: 我尝试使用 Angular 提供的 Injector class 但它对我不起作用。所以请帮忙。

使用 Injector 应该有效:

创建注入器:

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

为了测试,让我们 return 来自服务中 init 函数的字符串 test

init() {
  return 'test';
}

为了测试,在您的 class 中,您将使用注入器调用 init

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

最后组件调用 func1:

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

DEMO