代码之家  ›  专栏  ›  技术社区  ›  Always_a_learner

如何在订阅observable之前使用distinctUntilChanged检查json对象

  •  0
  • Always_a_learner  · 技术社区  · 6 年前

    我想订阅observable,只有当我从Observator subject接收到的JSON对象的值发生变化时:

     searchedName = '';
    
    
      filters = {
      "page": 1,
      "perPage": 10,
      "sortOrder": "asc",
      "tag": "allUsers",
      "sortBy": "firstname"
    }
      getUsers(e)
      {
        console.log("searched")
        const searchedKeyword = this.searchedName.trim();
        if(searchedKeyword !== '')
        this.filters['name'] = searchedKeyword
        this._service.triggerCallForUsers(this.filters)
      }
       ngOnInit()
    {
      //Initially called to load users..
       this._service.triggerCallForUsers(this.filters)
    
       //Subscribe to fetch users
        this._service.startFetchingUsers$
          .distinctUntilChanged()
          .subscribe((filters) => {
            console.log("filters", filters)
            if (filters) {
              this._service.getUsersByFilter(filters)
                .subscribe(
                  users => {
                    console.log('users', users);
    
                  },
                  error => {}
                );
            }
    
          })
    }
    

    这可能吗?

    尝试解决如下问题:

    .distinctUntilChanged((a, b) => {
      console.log('compare', b['name'], a['name'], b['name'] === a['name']);
      return a === b
    })
    

    输出:-没有用于比较的输出

    next()将包含

    过滤器['name']

    输出:-compare s undefined false

    //如果我将searchedName更改为“sd”:

    输出:-比较sd sd true。

       <input type="text" (keyUp.enter)="getUsers($event)" [(ngModel)]="searchedName">
    

    服务:

    private startFetchingUsers = new BehaviorSubject < any > (null);
    startFetchingUsers$ = this.startFetchingUsers.asObservable();
    
    
    
    triggerCallForCareGroup(filter) {
    
        this.startFetchingUsers .next(filter);
      }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   m1ch4ls    6 年前

    如果需要深度相等,请尝试使用 isEqual 来自洛达斯。

    subscribe do / tap 副作用和 mergeMap 用于合并其他可见光。

    import { isEqual } from 'lodash';
    
    this._service.startFetchingUsers$
        .distinctUntilChanged(isEqual)
        .do(filters => console.log("filters", filters))
        .mergeMap(filters => this._service.getUsersByFilter(filters))
        .do(users => console.log('users', users))
        .subscribe({
            error(error) {
                console.error(error);
            },
        });
    

    这表明您的代码中可能还有其他问题。你能在你打电话的地方分享密码吗 startFetchingUsers.next(newFilters) ?

    你在变异 this.filters a === b 始终保持。物体本身是一样的!像这样使用浅拷贝: this._service.triggerCallForUsers({ ...this.filters })