将服务作为Angular 4中所有组件的单例注入 [英] Inject service as singleton for all components in Angular 4
问题描述
对不起,如果有重复,我已经阅读了相关文章,但没有找到(或不理解)答案.
Sorry if duplicate, I've read related posts, but didn't find (or didn't understand) an answer.
我有许多组件使用的服务,并且希望它成为所有组件(贯穿所有应用程序)的单例. 此服务必须发送请求并获取一次数据,然后在其他组件之间共享此数据.
I have a service that is used by many components and I want it to be a singleton for all components (throughout all app). This service must send a request and get data once and then share this data among other components.
下面是一些代码示例:
app.module.shared.ts
import { MyService } from '../services/myservice';
@NgModule({
declarations: [
//...
],
imports: [
//...
],
providers: [
MyService
]
})
myservice.ts
@Injectable()
export class MyService {
shareData: string;
constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string) { }
getSharedData(): Promise<string> {
return new Promise<string>(resolve => {
if (!this.shareData) {
this.http.get(this.baseUrl + "api/sharedDara").subscribe(result => {
this.shareData = result.json() as string;
resolve(this.shareData);
}, error => console.log(error));
} else {
resolve(this.shareData);
}
});
}
}
example.component.ts (用法示例)
import { MyService } from '../services/myservice';
@Component({
selector: 'example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
sharedData: string;
public constructor(private myService: MyService,
@Inject('BASE_URL') private baseUrl: string) { }
ngOnInit() {
this.myService.getSharedData().then(result => this.sharedData= result);
}
}
文档说:
依赖性是注入器范围内的单例.
Dependencies are singletons within the scope of an injector.
据我了解,为每个组件创建了自己的服务实例.这样对吗?以及如何为所有组件创建一个服务实例?
As I understand that for each component its own instance of a service is created. Is it right? And how to make a single instance of a service for all components?
谢谢.
推荐答案
要将服务作为具有多个组件的单例使用:
- 导入
- 将其添加到组件构造器中
请勿将其作为提供程序添加到您的组件中.
DO NOT add it as a Provider to your component.
import { Service } from '../service';
@Component({
selector: 'sample',
templateUrl: '../sample.component.html',
styleUrls: ['../sample.component.scss']
})
export class SampleComponent implements OnInit {
constructor(private _service: Service) { }
要将服务用作每个组件中的新实例,您可以在中使用它:
- 导入
- 将其添加到组件构造器中
将其作为提供程序添加到您的组件中
DO add it as a Provider to your component
import { Service } from '../service';
@Component({
selector: 'sample',
templateUrl: '../sample.component.html',
styleUrls: ['../sample.component.scss'],
providers: [Service]
})
export class SampleComponent implements OnInit {
constructor(private _service: Service) { }
这篇关于将服务作为Angular 4中所有组件的单例注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!