Angular库中的服务和本地服务不同,主要是因为Angular库的服务是单例模式,而本地服务是每次都会创建一个新实例。为了解决这个问题,需要在Angular库中使用Injector创建每个服务的实例。
首先,需要在Angular库的服务提供商中将其标记为可被多重实例化,如下所示:
@Injectable({ providedIn: 'any' }) export class MyService { }
然后,在使用服务的地方,可以使用Injector创建新的实例:
import { Component, Injector } from '@angular/core'; import { MyService } from 'my-library';
@Component({
selector: 'my-component',
template:
})
export class MyComponent {
private myService: MyService;
constructor(private injector: Injector) { }
createService() { this.myService = this.injector.get(MyService); }
useService() { this.myService.doSomething(); } }
这样,每次点击“Create Service”按钮时,都会创建一个新的MyService实例。
下一篇:Angular库中的路径无效