【问题标题】:How to make sure that not concat duplicated objects in array?如何确保不连接数组中的重复对象?
【发布时间】:2017-04-11 13:15:49
【问题描述】:

我正在学习 Reactive Programming 使用 RxJs 并且需要一些帮助来找到适合这种情况的最佳操作员。我正在开发一个angular 4 应用程序并使用此方法:

  ngAfterViewInit() {
     this.returnUsers();
  }

  returnUsers() : void {
    this.userService.ListUsers(this.token)
        .subscribe(response => {
            this.token = response.token;
            this.users = this.users.concat(response.users);
        });
  }

  scrollDown() {
    this.returnUsers();
  }

功能还可以,问题是如果用户滚动太快,我发送到服务器的令牌是相同的,所以我连接重复的对象。我想知道如何处理它的最佳方法。我尝试使用.filter 运算符,也只连接不重复的对象,但我仍在访问服务器。

编辑: 我正在使用angular2-infinite-scroll

【问题讨论】:

  • 你试过 distinctUntilChanged 吗?
  • 我现在试过了,然后我将油门时间(在我使用的滚动组件的模板中)更改为 10ms,并且仍然向服务器发出多次重复请求。

标签: angular rxjs reactive-programming


【解决方案1】:

您是否在每个滚动事件上调用scrollDown() 方法?

如果是这样,那么您正在为每个滚动事件进行新订阅,这可能不是您想要的。
我认为您需要使用 Subject 实例并在每个滚动事件上推送一个值。然后你可以使用debounceTime(100) 来丢弃到达太快并且只有一个订阅的发射。

类似这样的东西(显然我没有测试这段代码,但我希望你能明白这一点)。

private subject$ = new Subject();

constructor() {
    this.subject$
        .debounceTime(100)
        .concatMap(() => this.userService.ListUsers(this.token))
        .subscribe(response => {
            this.token = response.token;
            this.users = this.users.concat(response.users);
        });
    });
}

scrollDown() {
    this.subject$.next();
}

【讨论】:

  • 它成功了,马丁,谢谢。我只是不明白为什么我需要在订阅行之后将this.subject$.next(); 放入构造函数中以获得第一个结果。应该在构造函数上调用 subscribe 方法吗?
  • @ggui this.subject$.next();scrollDown() 方法中,而不是在构造函数中
猜你喜欢
  • 2021-06-11
  • 2021-12-23
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2018-06-19
相关资源
最近更新 更多