我有一个方法返回如下所示的可观察值

constructor(private _http: HttpClient) {}

getUsers(location){
   return this._http.get(`https://someurl?location=${location}`)
          .pipe(
              map((response: any) => response),
              distinctUntilChanged()
           )
}

(请假定已导入所有必需的依赖项)

因此,为了显示用户结果,我调用loadUsers方法。
loadUsers(location){
   this.getUsers(location).subscribe( users => {
       this.userList = users;
    });
}

ngOnInit(){
    this.loadUsers('mumbai');
}

因此,上面的代码为我所有具有位置孟买的用户加载了用户列表。

现在,我在UI上有一个位置列表,旁边有复选框
Mumbai,
Delhi,
Kerala

因此,单击一个位置将调用以位置名称为参数的loadUsers方法。

因此,当我再次从复选框中单击孟买时(在单击除孟买以外的任何其他复选框之前),我不想再次加载属于孟买的用户,因为它已经加载了。

我读过在这种情况下可以使用distinctUntilChanged()。但是,它似乎对我不起作用,因为当我从复选框列表中选择孟买时,它仍然会命中来自孟买的loadUsers call

PS-这不是真正的用例。上面的描述只是为了使大家明白我的问题。

我是Angular和Rxjs的新手。请帮忙。

最佳答案

您的distinctUntilChanged将应用于响应this._http.get()返回。如果要防止在同一位置再次调用getUsers(),则必须稍微重写代码以使位置列表可观察到//将next位置推入主题,以便可以在此输入列表上使用distinctUntilChanged

const currentLocation = new Subject();
on('click', () => currentLocation.next(this.value)); // on your location list items checkboxes

currentLocation.pipe(
  distinctUntilChanged(),
  mergeMap(location => loadUsers(location)
)
.subscribe(users => {
  this.userList = users;
});

我在 Angular 方面遗漏了很多样板,但我希望您能了解解决方案的要点。

09-25 16:18