Rod*_*ras 8 casting view typescript angular angular9
我的组件中有一个变量,它在使用时正在更新,console.log(variable)
尽管它没有在我的视图中更新{{ variable }}
,但我已经尝试了几件事,我的最后一个选择是使用Observers
,但仍然无法正常工作。
我将解释我的代码:
所以我有一个服务、一个基础组件、一个应用程序组件和另一个组件
我的基本组件没有任何视图。它仅实例化服务。就像这样:
private _communicationService: CommunicationService;
private _clientService: ClientService;
constructor(private injector : Injector) {
this.clientService = this.injector.get(ClientService);
}
Run Code Online (Sandbox Code Playgroud)
(包括获取和设置)
我的应用程序组件和另一个扩展了 BaseComponent
我认为我的实现中的错误是接下来的事情:
我的应用程序组件正在调用window
我尝试在 ngInit 上实现的函数
export class AppComponent extends BaseComponent implements OnInit{
constructor(injector : Injector) {
super(injector);
}
ngOnInit(): void {
window.FlashExternalInterface.logLoginStep = (step : string) => {
this.clientService.loadClientProgress(step);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的“其他”组件:
export class LoaderComponent extends BaseComponent implements OnInit {
public progress = 0;
constructor(injector : Injector) {
super(injector);
}
ngOnInit(): void {
this.clientService.clientProgress.subscribe(data => {
console.log("Data Changing?: " + data);
this.progress = data;
console.log("Progress changing??" + this.progress);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我的progress
变量在 F12 控制台中确实发生了变化,但在视图中没有变化。
我尝试过使用{{ this.progress }}
AND 而不使用this.
甚至从基础组件调用直接服务实例clientService.clientProgress.getValue()
我的意思是,窗口函数在控制台中给我一个错误,例如:
ERROR TypeError: Cannot set property 'logLoginStep' of undefined.
Run Code Online (Sandbox Code Playgroud)
但是,该变量在控制台中确实发生了变化。 控制台变量
这可能是一个异步问题,因为progress
在调用中分配了一个值subscribe()
。在客户端返回数据之前,progress
不会被更新。
您工作的原因console.log
是因为它位于您的subscribe()
块内,因此根据定义,它在登录到控制台之前等待服务返回值。progress
然而,一旦页面加载,您的 HTML 就会被指示呈现当前值。即使你subscribe()
被称为内ngOnInit()
,服务仍然需要非零的时间来返回更新的值,这已经太晚了。
有几种方法可以在 HTML 中处理这个问题
异步管道
<p>{{ progress | async }}<p>
这将监视progress
变量的更新,并在值更新后直接将更改呈现到 DOM;实际上与什么相同.subscribe()
实际上与.ts 文件中的
* ngIf
<p *ngIf="progress">{{ progress }}</p>
<p>
在变量为真之前,这根本不会渲染progress
,即在本例中不是0
,null
或者undefined
归档时间: |
|
查看次数: |
11826 次 |
最近记录: |