【问题标题】:Why is my array changing after function return?为什么我的数组在函数返回后发生变化?
【发布时间】:2020-09-16 16:37:49
【问题描述】:

我有一个函数,我过滤一个数组,并在复选框的帮助下检查对象的属性liked 是否等于一个。

  async getGetLikedMatches(checked){
    if(checked){
      await this.sp.getReleases().subscribe(data => {
        this.allMatches = data;
        this.matches = data;
      });
      this.matches = this.allMatches.filter(match => match.favorit == 1);
      console.log({matches: this.matches, allMatches: this.allMatches}); // matches has correctly 6 
                                                                         // elements
      // after the fuction returns matches == allMatches -> 110 element
      // but why?
    }
    else if (!checked){
      await this.sp.getReleases().subscribe(data => {
        this.allMatches = data;
        this.matches = data;
      });
      console.log(this.matches)
    }

在我的 html 文件中,我遍历了这些匹配项:

        <div class="col-3" *ngFor="let match of matches">
            <img [src]="match.images == '' ? url : getImage(match)"
              alt="matches" 
             style="min-width: 200px; max-width: 200px; max-height: 200px; min-height: 200px;"
             (click)="onDetailView(match.id, selectedType)"/> <br />
        </div>

【问题讨论】:

    标签: javascript arrays angular typescript async-await


    【解决方案1】:

    我认为你错误地使用了 rxjs,试试这个

    getGetLikedMatches(checked) {
        this.sp.getReleases().subscribe(data => {
           this.allMatches = data;
    
           if (checked) {
               this.matches = this.allMatches.filter(match => match.favorit == 1);
           } else {
               this.matches = data;
           }
    
           console.log({ matches: this.matches, allMatches: this.allMatches });
    });
    

    }

    【讨论】:

    • 嘿,它正在工作!谢谢!我会标记你的答案,但你可能知道为什么我的代码没有按预期工作吗?
    • 因为订阅是不可等待的,你必须在订阅方法中处理数据。如果你想使用 await 你可以做 await this.sp.getReleases().toPromise();然后在数组上使用过滤器方法
    猜你喜欢
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2015-04-08
    相关资源
    最近更新 更多