服务内部有一个变量:
public currentLayers = new Map<TreeNode, RegistryLayerItemGeneric[]>();
我在响应后填写这个变量:
this.registryDataSource
.getRegistryPolygon(registry.Id, currentScale)
.subscribe((response) => {
this.currentLayers = this.hardPrepare(response);
});
如何在组件内部获取这些数据以在模板中呈现?
我试图直接从服务中获取变量:
public get currentLayers() {
return this.registryLayers.currentLayers;
}
然后在模板中使用:
<div *ngFor="let layer of currentLayers | keyvalue"></div>
但是这种方法每次在用户聚焦时都会呈现模板。
答案 0 :(得分:0)
您应该从服务返回一个 observable 并利用 html 模板中的 async pipe:
为您服务:
public currentLayers = AsyncSubject<TreeNode, RegistryLayerItemGeneric[]> = new AsyncSubject();
.
.
.
this.registryDataSource
.getRegistryPolygon(registry.Id, currentScale)
.subscribe((response) => {
this.currentLayers.next(this.hardPrepare(response));
});
模板:
<div *ngFor="let layer of registryDataSource.currentLayers | async | keyvalue"></div>
通过这种方式,您将获得异步管道的好处:自动更改检测和取消订阅组件销毁。 并且component.ts中也没有多余的代码。
请注意,对于封装,最好从服务返回 Observable 而不是 AsyncSubject。
在您的服务中,您应该:
public _currentLayers = AsyncSubject<TreeNode, RegistryLayerItemGeneric[]> = new AsyncSubject();
public get currentLayers(): Observable<TreeNode, RegistryLayerItemGeneric[]> {
return _currentLayers.asObservable()
}