The isEdit variable is assigned asynchronously. For inter dependent observables you could use RxJS higher order mapping operators (like switchMap) to map between them and filter operator to emit only if the edit parameter is true.
Try the following
export class ProductEditComponent implements OnInit {
uiProduct: ProductModel;
ngOnInit() {
this.activatedRoute.queryParams.pipe(
filter((queryParams: any) => (!!queryParams['edit'])), // <-- proceed only if `edit` is true
switchMap(_ => this.productService.GetProductByName(this.name))
).subscribe({
next: (response: ProductModel) => {
this.uiProduct = response;
},
error: (error: any) => {
// handle error
}
});
}
}
Update: use async query param elsewhere
Expanding from my comment, you need to maintain the async nature of the data to reuse it elsewhere in the code. You could use RxJS ReplaySubject with buffer 1. Also you need to make sure to close all open subscriptions when component is closed. I'm using takeUntil for it.
import { ReplaySubject, Subject } from 'rxjs';
import { tap, filter, switchMap, takeUntil } from 'rxjs/operators';
export class ProductEditComponent implements OnInit, OnDestroy {
uiProduct: ProductModel;
editSrc = new ReplaySubject<any>(1);
edit$ = this.editSrc.asObservable();
closed$ = new Subject<any>();
ngOnInit() {
this.activatedRoute.queryParams.pipe(
tap({ next: (queryParams: any) => { this.editSrc.next(queryParams['edit']) } }),
filter((queryParams: any) => (!!queryParams['edit'])), // <-- proceed only if `edit` is true
switchMap(_ => this.productService.GetProductByName(this.name))
).subscribe({
next: (response: ProductModel) => {
this.uiProduct = response;
},
error: (error: any) => {
// handle error
}
});
}
someFunc() {
this.edit$.pipe(
takeUntil(this.closed$)
).subscribe({
next: (edit) => {
if (edit) {
// do something
} else {
// do something else
}
}
});
}
someOtherFunc() {
this.edit$.pipe(
takeUntil(this.closed$)
).subscribe({
next: (edit) => {
if (edit) {
// do something
} else {
// do something else
}
}
});
}
ngOnDestroy() {
this.closed$.next(); // <-- close open subscriptions when component is closed
}
}