0

I want to get the profile id from the current url. I am doing something like

opaProfileId$ = this.activatedRoute.queryParamMap.subscribe((params) => +params.get('opaProfileId'));

then in template I want to compare it with a number like

<tr [ngClass]="{ 'highlight-row': profile.id === opaProfileId$ | async as number }" *ngFor="let profile of data">

but it throws error. Any ideas how to do it with observable?

Rishav Tandon
  • 105
  • 1
  • 10
  • 1
    Don't subscribe, that is what the `async` pipe does for you (and unsubscribes) Now you are assigning a subscription to `opaProfileId$.` – AT82 Nov 23 '21 at 11:01
  • Just saying `it throws error` without providing the error is not very helpful. It's like saying "It doesn't work" – Jeremy Thille Nov 23 '21 at 11:01

1 Answers1

3

You cannot combine subscription in component and async pipe in template.

Subscription in component controller

You either subscribe in the component controller or use async in template. While subscribing in controllers, it'd serve you better to close the subscription when the component is closed. See here for more info.

opaProfileId: number;

this.activatedRoute.queryParamMap.subscribe((params) => 
  this.opaProfileId = +params.get('opaProfileId')
);
<tr [ngClass]="{ 'highlight-row': profile.id === opaProfileId }" *ngFor="let profile of data">

async pipe

While using async pipe, you'd need to use the RxJS map operator for fetching the query param and type casting. While using async, explicitly closing the subscription isn't necessary. async pipe takes care of it.

opaProfileId$: Observable<number>;

this.opaProfileId$ = this.activatedRoute.queryParamMap.pipe(
  map((params) => +params.get('opaProfileId'))
);
<tr [ngClass]="{ 'highlight-row': profile.id === (opaProfileId$ | async) }" *ngFor="let profile of data">
ruth
  • 29,535
  • 4
  • 30
  • 57