gpt4 book ai didi

javascript - Angular 和 Observable : how to avoid multiple requests to API within a given time

转载 作者:数据小太阳 更新时间:2023-10-29 04:43:27 25 4
gpt4 key购买 nike

我在 Angular 4 应用程序中有类似的东西(为了示例,我删除了代码)

@Injectable()
export class SomeService {

constructor(
private http: Http
) {
}

get(id: number) {
return this.http.get('http://somedomain/somemodel/${id}.json');
}

}

一些组件使用它来进行 API 调用。

constructor(private someService: SomeService) {}
...
someMethod() {
// code here...
this.someService.get(2).subscribe( someHandlerFunction );
}

someOtherMethod() {
// more code here...
this.someService.get(2).subscribe( someHandlerFunction );
}

问题是我不知道什么时候会调用 someMethod() 和 someOtherMethod()。有时它们都可能被调用,然后我的 API 将被调用两次。我试图找到的是,是否有任何方法可以更改我的服务以仅在 X 时间后才执行此请求。我尝试使用去抖:

get(id: number) {
return this.http.get(`http://somedomain/somemodel/${id}.json`).debounceTime(10000);
}

预计(在本例中)此 HTTP get 请求只会在 10 秒后重复,如果请求是在这 10 秒内发出的,则请求不会重复,但可观察对象会发出最后一个值。但这没有用。有什么建议吗?

PS:我知道我可以使用某种标志来控制它,但只要它的扩展性不是很好,我就不能这样做。我有多个包含大量 HTTP 请求的服务。

对此有什么想法吗?

最佳答案

Debounce 应该用在调用 http 服务的 observable 上,而不是用在 http 请求本身上。例如:

someObservable
.valueChanges
.debounceTime(1000)
.subscribe(// Call the http service here)

对先前提出的问题提供了更好的解释 here .

关于javascript - Angular 和 Observable : how to avoid multiple requests to API within a given time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236692/

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