Home > Mobile >  Angular: Looking for a better way to search by id
Angular: Looking for a better way to search by id

Time:07-20

I search by id in this way:

ngOnInit(): void {
    this.route.queryParamMap.subscribe(
      params => {
        const id = params.get('id');
        if (id) {
          this.contactsService.GetContactByUserId(id)
            .subscribe(
              response => {
                this.contact = response;
              }
            )
        }
      }
    )
  }

I did not like that I have subscribe within subscribe and it also causes some bugs I would like to better solutions

CodePudding user response:

Use switchMap

this.route.queryParamMap.pipe(
  map(params => params.get('id')),
  filter(Boolean),
  switchMap(id => this.contactsService.GetContactByUserId(id)),
).subscribe(response => this.contact = response);
  • Related