[英]How to initialize a variable once on the app.module using a service and use it later in other components?
I have a list of objects to be generated once in the application startup from a backend API using a service, the question is how to initialize that list and access it from the other components? 我必须从后端API使用服务的应用程序启动一次生成的对象列表,问题是如何初始化与其他组件列表和访问它?
For example, in app.module.ts, I want something like: 例如,在app.module.ts中,我想要类似以下内容:
export class AppComponent {
title = 'General Title';
myListFromServiceApi:[DataType];
}
How to call this in mycomponent.ts 如何在mycomponent.ts中调用它
ngOnInit() {
this.myListFromServiceApi= ??
}
Edit 编辑
I already have the service, but I want to avoid invoking the service every time the component added to a view, ie call the service once in the lifetime of the application if that is possible, how can I achieve that? 我已经拥有该服务,但是我想避免每次将组件添加到视图时都调用该服务,即,如果可能的话,在应用程序的生命周期中调用一次服务,我该如何实现?
You could use the rx operator share
that prevents a sideeffect (http request in your case) from being executed multiple times on subscription of multiple subscribers and return an observable that's piped through a share
from a service, ie DataTypeService
: 您可以使用rx运算符
share
来防止在订阅多个订阅者时多次执行副作用(在您的情况下为http请求),并返回通过服务share
(即DataTypeService
通过管道传递的可观察对象:
export class DataTypeService {
dataTypes$: Observable<DataType>;
constructor(private http: HttpClient) {
this.dataTypes$ = this.http.get('/api/datatypes').pipe(share());
}
getDataTypes() {
return this.dataTypes$;
}
}
In your components you could then inject the DataTypeService
, subscribe to the observable returned by getDataTypes()
and the request would only be executed once. 然后,您可以在组件中注入
DataTypeService
,订阅由getDataTypes()
返回的getDataTypes()
并且该请求将仅执行一次。
constructor(private dataTypeService: DataTypeService){
this.dataTypeService.getDataTypes().subscribe(dataTypes => {
this.myListFromServiceApi = dataTypes;
})
}
If you only wanna work with those data types in your template you could also directly store the observable returned by getDataTypes()
on your component and utilize the async
pipe 如果只想在模板中使用这些数据类型,则还可以将
getDataTypes()
返回的observable直接存储在组件中,并利用async
管道
See this stackblitz . 看到这个堆叠闪电战 。 Generally you have one sharedService.
通常,您只有一个sharedService。 That will request the data once and store it as a local variable.
这将请求一次数据并将其存储为局部变量。 Two other components (first and second) only Inject the service in the constructor and keep a reference to the member variable inside a sharedService.
仅其他两个组件(第一个和第二个)将服务注入构造函数中,并在sharedService中保留对成员变量的引用。 This way http call goes out only once.
这样,http调用只会发出一次。 Invoked in:
调用于:
ngOnInit() {
this.sharedService.getDataOnce();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.