re: How to filter requests in Angular? VIEW POST

FULL DISCUSSION
 

If you need to switch between multiple possible values, I think you don't have a choice. But, if you want only to emit when you have res.length larger than 0, I think you can use filter operator.

getExperiences() {
  this.experienceService.listApprovedExperiences().subscribe((res) => {
    this.experiences = res;
    for (const experience of res) {
      this.getSessionList(experience.id);
    }
  });
}

getSessionList(id: string) {
  this.experienceService.getSessionListByExperienceId(id).pipe(
    filter(res => res.length > 0), // only emits a value if length is larger than 0
  ).subscribe(res => {
    this.session.set(id, res[0]);
  });
}

You could also map operator to do something like

getExperiences() {
  this.experienceService.listApprovedExperiences().subscribe((res) => {
    this.experiences = res;
    for (const experience of res) {
      this.getSessionList(experience.id);
    }
  });
}

getSessionList(id: string) {
  this.experienceService.getSessionListByExperienceId(id).pipe(
    map(res => res.length > 0 ? res[0] : aDefaultValue ) // emits res[0] data, or a default value if res is not an array like.
  ).subscribe(data => {
    this.session.set(id, data);
  });
}

Or you could combine both operators and do something like

function getExperiences() {
  this.experienceService.listApprovedExperiences().subscribe((res) => {
    this.experiences = res;
    for (const experience of res) {
      this.getSessionList(experience.id);
    }
  });
}

function getSessionList(id: string) {
  this.experienceService.getSessionListByExperienceId(id).pipe(
    filter(res => res.length > 0), // emits only if res.length is larger than 0
    map(res => res[0]), // emits the actual data in res[0]
  ).subscribe(data => {
    this.session.set(id, data);
  });
}

There are several operators that you can use with rxjs. Just notice that some of them are deprected in recent version 6, and you may find them in current documentations, and tutorials. However, version 6 was release a couple of days ago, so you probably won't need them.

 

Thank you so much!! Your comment was quite useful for me. So , I will try my best and after reviewing the documentation,I will update the post the possible solutions that comes with Angular 6 :)

 

Just for you to notice, I'm referring to rxjs@6, that just be casualty happens to have the same number version as Angular, but this breaking change is not because Angular@6

code of conduct - report abuse