我需要一个共同的服务在所有其他服务。共同事务只启动一次。
让我们说共同的服务是-
export Class CommonService
{
_commonVar1= "";
_commonVar2= "";
}
现在,在所有其他服务中都需要公共服务实例。记住-公益服务将只启动一次。
发布于 2017-11-28 12:44:27
如果将服务放入提供程序数组,则只实例化它们一次。他们基本上是单身。您可以像这样在应用程序模块中注册服务。
providers: [ArticleService, Category1Service, Category2Service],
在接下来的步骤中,我们将在类声明的顶部使用@Injectable()装饰器来让角知道类可以被注入。
然后使用@ inject ()将以下服务注入另一个服务,如下面所示。
import { Injectable, Inject } from '@angular/core';
@Injectable()
export class ArticleService {
public name: string;
constructor() {
this.name = "Awesome article";
};
}
@Injectable()
export class Category1Service {
constructor(@Inject(ArticleService) public articleService: ArticleService) { }
}
@Injectable()
export class Category2Service {
constructor(@Inject(ArticleService) public articleService: ArticleService) { }
}
因为我们的商品服务注册为单例,以下是正确的。
export class FooComponent {
constructor(
@Inject(ArticleService) private articleService: ArticleService,
@Inject(Category1Service) private category1Service: Category1Service,
@Inject(Category2Service) private category2Service: Category2Service,) {
// both will print "Awesome article"
console.log(category1Service.articleService.name);
console.log(category2Service.articleService.name);
// change name in article service
articleService.name = "Bad article";
// both will print "Bad article"
console.log(category1Service.articleService.name);
console.log(category2Service.articleService.name);
}
}
https://stackoverflow.com/questions/47530226
复制相似问题