Angular2和数组过滤/查找

时间:2017-01-21 11:16:06

标签: angular typescript

我有onInit处理,其中一些DB数据被调用然后组合在一起。我无法在此处粘贴整个方法,因为它格式不正确。

u.skills.forEach(s => {
    let skillEntry: SkillEntry = new SkillEntry();
    skillEntry.skill = s;

    let sbs: SkillBase[] = this.cachedSkillBases.filter(sb => sb.id == s.skillBaseId);
    if (sbs.length>0) {
      skillEntry.skillBase = sbs[0];
    } else {
      console.log('not found');
      this._userService.getSkillBase(s.skillBaseId).toPromise()
        .then(res => {
          skillEntry.skillBase = res;
          this.cachedSkillBases.push(res);
        });
    }
});

我在这里实施了临时缓存以加快速度,但搜索它并不起作用。具体来说,我不知道为什么这个过滤不起作用,如果变量'存在且始终具有正确的ID

let sbs: SkillBase[] = this.cachedSkillBases.filter(sb => sb.id == s.skillBaseId);

这是我在这里失踪的吗?

2 个答案:

答案 0 :(得分:0)

您的缓存实现是异步的,这意味着在循环期间您将获得100%缓存未命中和多个重复请求。承诺then执行异步或稍后执行

答案 1 :(得分:0)

好的,这是我的完整方法。我知道数据在第一次运行时不可用,但为什么我的本地缓存不起作用,它看起来像是空的还是这样? 不幸的是我无法立即粘贴整个方法,因为它被此页面拒绝(格式不正确)。在此处粘贴的上面我只有方法声明,而缓存数组是在组件级别声明的。

** private getUsers(){***

let fetchedUsers: User[];

let userEntries: UserEntry[] = [];
let skillEntries: SkillEntry[];

this._userService.getAllUsers(this.searchForm.userName, this.searchForm.skillName, this.searchForm.groupName)

  .toPromise()

  .then(result => {
    fetchedUsers = result;
    fetchedUsers.forEach(u => {
      let userEntry: UserEntry = new UserEntry();
      userEntry.detail = u;

      skillEntries = [];
      u.skills.forEach(s => {
        let skillEntry: SkillEntry = new SkillEntry();
        skillEntry.skill = s;

        let sbs: SkillBase;
        Promise.all(this.cachedSkillBases).then(res => {
          sbs = res.find(sb => sb.id == s.skillBaseId);
        });

        if (sbs) {
          skillEntry.skillBase = sbs;
        } else {
          this._userService.getSkillBase(s.skillBaseId).toPromise()
            .then(res => {
              console.log('got skills');
              skillEntry.skillBase = res;
              this.cachedSkillBases.push(res);
            });
        }

        if (s.skillDetailId) {
          let sds: SkillDetail;
          Promise.all(this.cachedSkillProficiencies).then(res => {
            sds = res.find(sd => sd.id == s.skillDetailId);
          });
          if (sds) {
            skillEntry.skillProficiency = sds;
          } else {
            this._userService.getSkillProficiency(s.skillDetailId).toPromise()
              .then(res => {
                console.log('got proficiencies');
                skillEntry.skillProficiency = res;
                this.cachedSkillProficiencies.push(res);
              });
          }
        }
        skillEntries.push(skillEntry);
      });
      console.log('setting users');
      userEntry.skills = skillEntries;
      userEntries.push(userEntry);
    })
  })
  .then(res => this.users = userEntries);