我在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秒内发出请求,则该请求将不会重复,但是observable会发出最后一个值。但这是行不通的。
有小费吗?

PS:我知道我可以使用某种标志来控制它,但是只要它不能很好地缩放,就不能这样做。我有许多带有许多HTTP请求的服务。

有什么想法吗?

最佳答案

应该在调用http服务的可观察对象上使用反跳,而不是在http请求本身上使用。因此,例如:

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

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

10-06 07:23
查看更多