在非角色类中使用服务

问题描述 投票:1回答:1

我正在使用Angular v7.3.5,我想在非Angular类中使用Service,如下所示:

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类,但它对我不起作用。所以请帮忙。

angular typescript angular-services
1个回答
1
投票

使用Injector应该工作:

创建注入器:

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

为了测试,让我们从服务中的init函数返回字符串test

init() {
  return 'test';
}

为了测试,在你的课堂上你可以使用注射器调用init

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

最后调用func1的组件:

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

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.