提问人:Rodolfo Contreras 提问时间:8/4/2020 最后编辑:Rodolfo Contreras 更新时间:9/13/2023 访问量:11285
Angular 9 变量未在 View 中更新
Angular 9 Variable not updating in View
问:
我的组件中有一个变量,它在使用时正在更新,尽管它没有在我的视图中使用更新,我已经尝试了几件事,我的最后一个选择是使用,但仍然无法正常工作。console.log(variable)
{{ variable }}
Observers
我将解释我的代码:
所以我有一个服务,一个基础组件,一个应用程序组件和另一个组件
我的基本组件没有任何视图。它只实例化服务。就像这样:
private _communicationService: CommunicationService;
private _clientService: ClientService;
constructor(private injector : Injector) {
this.clientService = this.injector.get(ClientService);
}
(包括 get 和 setter)
My App Component 和另一个扩展了 BaseComponent
我认为在我的实现中是错误的是下一件事:
我的应用程序组件正在调用我尝试在ngInit上实现的函数window
export class AppComponent extends BaseComponent implements OnInit{
constructor(injector : Injector) {
super(injector);
}
ngOnInit(): void {
window.FlashExternalInterface.logLoginStep = (step : string) => {
this.clientService.loadClientProgress(step);
}
}
}
我的“其他”组件:
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);
});
}
}
我的变量在 F12 控制台中确实发生了变化,但在视图中没有。progress
我尝试过在没有 AND 的情况下使用,甚至从 Base Component 调用直接服务实例{{ this.progress }}
this.
clientService.clientProgress.getValue()
我的意思是,窗口函数在控制台中给了我一个错误,例如:
ERROR TypeError: Cannot set property 'logLoginStep' of undefined.
但是,该变量在控制台中仍然发生了变化。控制台变量
答:
这可能是一个异步问题,因为在调用中分配了一个值。在从客户服务返回数据之前,不会更新。progress
subscribe()
progress
你的工作原因是因为它在你的块内,因此根据定义,它是在登录到控制台之前等待服务返回值。但是,您的 HTML 被指示在页面加载后立即呈现 的当前值。即使 your 被调用,服务仍然需要非零时间才能返回更新的值,这已经太晚了。console.log
subscribe()
progress
subscribe()
ngOnInit()
有几种方法可以在 HTML 中处理此问题
异步管道
<p>{{ progress | async }}<p>
这将监视变量的更新,并在值更新后直接将更改呈现给 DOM;实际上与.ts文件中的相同progress
.subscribe()
*ngIF的
<p *ngIf="progress">{{ progress }}</p>
在变量为真之前,这根本不会呈现 ,即在这种情况下不是 ,或者<p>
progress
0
null
undefined
评论
window.FlashExternalInterface.LogLoginStep