更新时间:2023-11-24 23:41:46
如果将服务放入提供者数组,则它们仅被实例化一次.他们基本上是单身.您可以像这样在应用模块中注册服务.
If you put service into providers array they are instantiated only once. They are basically singleton. You register services in app module like this.
providers: [ArticleService, Category1Service, Category2Service],
下一步,我们将在类声明的顶部使用@Injectable()装饰器,以使angular知道可以注入类.
In next step we will use @Injectable() decorator on top of class declaration to let angular know that class can be injected.
然后使用@Inject()将以下服务注入到另一个服务中,例如下面的示例.
And then inject following service to another service using @Inject() as in example bellow.
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) { }
}
因为我们的Article服务已注册为单例,所以是正确的.
Because our Article service is registered as singleton following is true.
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);
}
}