gpt4 book ai didi

Using valueChanges for API call(使用valueChanges进行API调用)

转载 作者:bug小助手 更新时间:2023-10-25 17:48:03 32 4
gpt4 key购买 nike



I have a situation when I need to listen to changes of a date input and for that I use valueChanges and subscribe to it. On each change I need to make an API call to backend in order to calculate an additional item.

当我需要监听日期输入的更改时,我会遇到这种情况,为此,我使用valueChanges并订阅它。每次更改时,我都需要对后端进行一次API调用,以便计算一个附加项。


From my understanding subscribing inside a subscribe is not a good practice, however what would be a better solution for this? Using (change) on date input instead?

根据我的理解,在订阅中订阅不是一个好的做法,然而,对于这个问题,什么会是更好的解决方案?是否改用日期输入上的(更改)?


Example:

示例:


private foo() {
this.form.controls['dateInput'].valueChanges.subscribe(date => {
if(date) {
this.api.doSomehting().subscribe(res => {
console.log(res)
})
}
})
}

更多回答
优秀答案推荐

Here is what I would do:

以下是我会做的事情:




private valueChangesSubscription: Subscription;

private foo() {
this.valueChangesSubscription = this.form.controls['dateInput'].valueChanges.subscribe(date => {
if(date) {
this.api.doSomehting().pipe(take(1)).subscribe(res => {
console.log(res)
})
}
})
}

OnDestroy() {
if (this.valueChangesSubscription) {
this.valueChangesSubscription.unsubscribe();
}
}




The take(1) operator automatically unsubscribes itself after the first result returns. So you don't have a memory leak.

Take(1)运算符在第一个结果返回后自动取消订阅。所以您不会有内存泄漏。


But you should remember to unsubscribe from your valueChanges observable since that one stays alive.

但你应该记住取消订阅你的值可观察到的变化,因为那个值还活着。


更多回答

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