[英]Angular ngOnchanges calls method, but method does not call service or output results
我對我的應用程序的一部分發生的事情感到困惑。 我有一個使用 ngOnChanges 的組件。 當組件加載時,ngOnchanges 在 ngOnInit 之前觸發。 ngOnChanges 和 ngOnInit 都調用某個方法 (fetchResults),該方法調用 api 服務以使用可觀察的返回來獲取一些數據。 我tap
了對服務的調用,以控制台記錄返回的數據以及調用 api 方法的 vs 中的斷點。
當從ngOnChanges
掛鈎對fetchResults
進行初始調用時,服務不會返回任何數據,並且不會命中 api 斷點。 但是,當觸發ngOnInit
鈎子並再次調用fetchResults
時,會命中 api 斷點,並且控制台日志會顯示返回的數據。
為什么會這樣? 我期待任何對fetchResults
的調用都會到達 api 並返回數據。 我已經驗證了所需的參數正在被傳遞。 來自ngOnChanges
ngOnInit
調用是相同的。
示例代碼:
ngOnInit() {
console.log('fetchResults called from ngOnInit')
this.fetchResults(this.itemId);
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges called with changes value: ', changes)
this.fetchResults(changes['propName'].currentValue)
}
fetchResults(itemId){
console.log('fetchResults function called with competitionId: ', itemId)
this.resultList$ = this.dataservice.getResults(itemId)
.pipe(
map( result => {
return result.map(
item => {
return item;
}
)
}),
tap(val => console.log(' fetchResults function - the value of returned result object: ', val))
)
}
結果組件 Html 與異步綁定:
... this.resultList$ | async" ...
我猜第二次調用 fetchResults方法(當 ngOnChanges 執行它時),您的可觀察屬性resultList$被“重新分配”給新的可觀察 object。
無論如何,如果您想測試您是否真的兩次都獲得數據,請更改您的fetchResults方法以隨時獲得不同的訂閱(僅用於測試):
fetchResults(itemId){
console.log('fetchResults function called with competitionId: ', itemId)
this.dataservice.getResults(itemId)
.pipe(
map( result => {
return result.map(
item => {
return item;
}
)
})
).subscribe(
val => console.log(' fetchResults function - the value of returned result object: ', val)
)}
最后,如果你想“修復”它,你可以這樣做:
// In your declaration of Class attributes:
get resultList$(itemId){
return this.dataservice.getResults(itemId)
.pipe(
map( result => {
return result.map(
item => {
return item;
}
)
}),
tap(val => console.log(' fetchResults function - the value of returned result object: ', val))
);
}
Class...
Cosntructor....
ngOnInit() {
console.log('fetchResults called from ngOnInit')
this.resultList$ = this.itemId;
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges called with changes value: ', changes)
this.resultList$ = changes['propName'].currentValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.