繁体   English   中英

角度变量值更改未反映在 DOM 中

[英]Angular variable value change doesn't reflect in DOM

我有一个 Angular 组件( SummaryComponent ),它注入了一个服务( LicenseRequestService )。 组件的变量 ( totalLicense ) 被定义为等于来自服务的计算字段。

组件类编写如下:

import { Component, OnInit } from '@angular/core';
import { LicenseRequestService } from '../shared/license-request.service';

@Component({
  selector: 'sg-summary',
  templateUrl: './summary.component.html',
  styleUrls: ['./summary.component.css']
})
export class SummaryComponent implements OnInit {

  constructor(private _service : LicenseRequestService) {

   }

   public totalLicense= this._service.licenseDetails.length


  ngOnInit(): void {
    
  }

  updateSummary(){
    const licenses= this._service.licenseDetails.length
    console.log("total players requested : " + players)
    this.totalLicense= players
  }

}

我已将totalLicense值嵌入到 DOM 中,如下所示:

<div>
    Total number of licenses is : {{totaLicense}}
</div>

<button type="submit" (click)="updateSummary()">Get licenses</button>

每次服务更新时,我都希望 DOM 反映更新后的totalLicense值,但它保持为 0。但是,当我单击标记为Get licenses的按钮时,DOM 随即更新,并且totaLicense变量在浏览器中显示新值。

我是否需要进行任何更改以确保在不单击按钮的情况下更新totalLicense的值(这是所需的功能)?

尝试把这个public totalLicense= this._service.licenseDetails.length代码constructorngOnInit

您的问题是您没有传递引用,而是传递了一个值。 基本上,如果你有以下几点:

 let x = 'test'; let y = x; x = 'update'; console.log(y);
此代码将输出 'test',而不是 'update',因为 y 仍指向原始值

我可以临时想到三种解决方案:

  1. 在 html 中引用服务本身(您必须将其设为非私有)
  2. 改为在组件中添加 licenseDetails 作为变量。 这样,当您访问长度变量时,它将通过引用,而不是通过值
  3. 使用 getter(不建议使用,因为它是反模式,因为它会导致函数在每个更改检测周期运行)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM