我有一個SummaryComponent注入了服務 ( LicenseRequestService)的 Angular 組件( )。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無需單擊按鈕即可更新的值(這是所需的功能)?
uj5u.com熱心網友回復:
嘗試放置此public totalLicense= this._service.licenseDetails.length代碼constructor或ngOnInit
uj5u.com熱心網友回復:
您的問題是您沒有傳遞參考,而是傳遞了一個值。基本上,如果你有以下幾點:
let x = 'test';
let y = x;
x = 'update';
console.log(y);
此代碼將輸出“測驗”,而不是“更新”,因為 y 仍指向原始值
我可以臨時想到三種解決方案:
- 在 html 中參考服務本身(您必須將其設為非私有)
- 改為在組件中添加 licenseDetails 作為變數。這樣,當您訪問長度變數時,它將通過參考,而不是通過值
- 使用 getter(不建議使用,因為它是反模式,因為它會導致函式在每個更改檢測周期運行)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339569.html
