gpt4 book ai didi

Angular 9 变量未在 View 中更新

转载 作者:行者123 更新时间:2023-12-03 20:50:18 25 4
gpt4 key购买 nike

我的组件中有一个变量,它在使用 console.log(variable) 时正在更新虽然它没有使用 {{ variable }} 在我的 View 中更新我尝试了几件事,我的最后一个选择是使用 Observers并且仍然无法正常工作。
我将解释我的代码:
所以我有一个服务、一个基础组件、一个应用组件和另一个组件
我的基本组件没有任何 View 。它只实例化服务。就像这样:

  private _communicationService: CommunicationService;
private _clientService: ClientService;

constructor(private injector : Injector) {
this.clientService = this.injector.get(ClientService);
}
(包括 get 和 setter)
我的 App 组件和另一个,扩展了 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);
}
}
}
我的“其他”组件:
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);
});
}
}
我的 progress变量在 F12 控制台中确实发生了变化,但在 View 中没有变化。
我试过使用 {{ this.progress }}并且没有 this.甚至从基础组件调用直接服务实例 clientService.clientProgress.getValue()我的意思是,窗口函数在控制台中给了我一个错误,例如:
ERROR TypeError: Cannot set property 'logLoginStep' of undefined.
但是,变量确实在控制台中发生了变化。
Console Variables

最佳答案

这可能是一个异步问题,如 progresssubscribe() 中分配了一个值称呼。在从客户端服务返回数据之前,progress不会被更新。
你的原因console.log正在工作是因为它在您的 subscribe() 内块因此根据定义等待服务在登录到控制台之前返回值。但是,您的 HTML 被指示呈现 progress 的当前值。一旦页面加载完毕。即使您的 subscribe()ngOnInit() 内被调用,服务返回更新值仍然需要非零时间,这已经太晚了。
有几种方法可以在您的 HTML 中处理此问题
异步管道 <p>{{ progress | async }}<p>这将观看progress用于更新的变量并在值更新后直接将更改呈现给 DOM;实际上与 .subscribe() 相同在你的 .ts 文件中
* ngIf <p *ngIf="progress">{{ progress }}</p>这不会呈现 <p>直到progress变量是真实的,即在这种情况下不是 0 , nullundefined

关于Angular 9 变量未在 View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63237945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com