ngOnInit(): void { this.featureInventoryProductsTableEnabled =…
- User
ngOnInit(): void { this.featureInventoryProductsTableEnabled = checkFeatureFlag(SubstanceFeatureFlag.LIST_INVENTORY_MODE); this.isShowLoading = true; this.localeString = this.cookieHelper.getStore('languageCulture'); this._listeningEvent(); this._checkPermission(); this._getCompanyProfile(); this.checkDevice();
this.globalService.subUserProfile().pipe(takeUntil(this.ngUnsubscribe)).subscribe(userProfile => { this.userId = userProfile.id?.toString(); const lastViewModeMobile = localStorage.getItem(`${this.userId}${Constants.localStorageKey.LAST_VIEW_MODE_MOBILE_SUBSTANCE_INDEX}`); if (lastViewModeMobile) { this.selectedViewMode = this.listViewMode.find(item => item.id === +lastViewModeMobile); } this.route.params.pipe(takeUntil(this.ngUnsubscribe)).subscribe(async params => { if (environment.server.isAnonymous && StringHelper.isValidGUID(params['locationId'])) { await this.globalService.subLocations(true, true, [params['locationId']]); } this.isShowLoading = true; this.isChangingLocation = true; this.inputSearch.pageIndex = this.substancePageIndex = 0; this.setPaginator(0); console.log(params, 'params'); if (StringHelper.isValidGUID(params['locationId']) && params['locationId'] !== this.allText) { this.locationId = params['locationId']; console.log(this.locationId, 'locationId 111'); this.inputSearch.locationIds = []; this.inputSearch.locationId = this.locationId; this.globalService.submitActiveLocation(this.locationId); this.globalService.setLocationIdToLocalStorage(this.locationId); this.globalService.locationList$.pipe(takeUntil(this.ngUnsubscribe)).subscribe(allLocation => { if (!this.checkLocationExisted(allLocation)) { this.router.navigate([this.isAnonymous ? '/not-permission' : '/substance/all']); return; } console.log(this.locationId, params, 'locationId'); this.globalService.getLocationByIdNotIncludeChemicals(this.locationId, true).pipe(takeUntil(this.ngUnsubscribe)).subscribe((locationDetail) => { if (!locationDetail) { return; } locationDetail.locationAttribute = locationDetail.locationAttribute || []; this.locationDetail = locationDetail; console.log(this.locationDetail, 'locationDetail'); const lastActivedTab = localStorage.getItem(`${this.userId}${Constants.localStorageKey.LAST_ACTIVED_TAB}`); if (this.isShowWATab) { const request: GetCountWorkAssignmentInLocationRequest = new GetCountWorkAssignmentInLocationRequest(); request.locationId = this.locationId; this.waService.getCountWorkAssignmentInLocation(request).pipe(takeUntil(this.ngUnsubscribe)).subscribe((result) => { this.isDisableWATab = !result; if (lastActivedTab) { this.activeTab = this.isDisableWATab ? this.activeSubstanceTab.id : +lastActivedTab; } }); } else { this.activeTab = lastActivedTab ? +lastActivedTab : this.activeSubstanceTab.id; } combineLatest( this.globalService.locationList$, this.globalService.echa_substances$, this.globalService.getChemicalDBConfigurationByNames([Constants.ExpiredSubstance, Constants.ConflictSubstanceWithSubstance, Constants.CheckMixturesChemicals]), ).pipe(takeUntil(this.ngUnsubscribe)).subscribe(async ([allLocation, substanceFromECHAPIC, configs]) => { this.allLocation = allLocation; this.listSubstanceFromECHAPIC = substanceFromECHAPIC; this.configExpiresYear = configs.find(config => config.name === Constants.ExpiredSubstance); this.showConflictChemicalAndChemical = configs.find(config => config.name === Constants.ConflictSubstanceWithSubstance)?.status; this.isCheckMixturesChemical = configs.find(config => config.name === Constants.CheckMixturesChemicals)?.status; if (this.locationDetail && this.allLocation.filter(x => x.id == this.locationDetail?.id).length > 0) { this._initBreadcrumbData(); } }, (error) => { console.error(error); }); }, (error) => { console.error(error); }); }); } else if (params['locationId'] !== this.allText) { this.router.navigate([this.isAnonymous ? '/not-permission' : '/substance/all']); return; } else { this.locationId = null; this.locationDetail = null; this.inputSearch.locationId = null; combineLatest( this.globalService.locationList$, this.globalService.echa_substances$, this.globalService.getChemicalDBConfigurationByNames([Constants.ExpiredSubstance, Constants.ConflictSubstanceWithSubstance, Constants.CheckMixturesChemicals]), ).pipe(takeUntil(this.ngUnsubscribe)).subscribe(async ([allLocation, substanceFromECHAPIC, configs]) => { this.allLocation = allLocation; this.listSubstanceFromECHAPIC = substanceFromECHAPIC; this.configExpiresYear = configs.find(config => config.name === Constants.ExpiredSubstance); this.showConflictChemicalAndChemical = configs.find(config => config.name === Constants.ConflictSubstanceWithSubstance)?.status; this.isCheckMixturesChemical = configs.find(config => config.name === Constants.CheckMixturesChemicals)?.status; if (this.locationDetail && this.allLocation.filter(x => x.id == this.locationDetail?.id).length > 0) { this._initBreadcrumbData(); } }, (error) => { console.error(error); }); } }, (error) => { console.error(error); }); }); if (this.featureInventoryProductsTableEnabled) { this.loadFontFamily(); } }when i click to other detail from '9cb9dc94-2709-46a6-a8c2-de82e402652d' to '821490e7-bab1-49f5-acd4-1c2b3a58f28d' it has issue, why '9cb9dc94-2709-46a6-a8c2-de82e402652d' is called first 9cb9dc94-2709-46a6-a8c2-de82e402652d {locationId: '9cb9dc94-2709-46a6-a8c2-de82e402652d'} locationId {locationId: '821490e7-bab1-49f5-acd4-1c2b3a58f28d'} 'params' 821490e7-bab1-49f5-acd4-1c2b3a58f28d locationId 111 821490e7-bab1-49f5-acd4-1c2b3a58f28d {locationId: '821490e7-bab1-49f5-acd4-1c2b3a58f28d'} locationId
if i try to setTimout({this.globalService.getLocationByIdNotIncludeChemi...}, 100), this is working
- Assistant
The issue you're experiencing is a classic race condition in Angular with nested observables. Here's what's happening:
Root Cause
When you navigate from one location to another, the
route.paramsobservable emits the new parameter, but theglobalService.locationList$observable inside the nested subscription is still processing the previous location's data. This creates a timing issue where:- New route params arrive (
821490e7-bab1-49f5-acd4-1c2b3a58f28d) - But
locationList$subscription still has the old location ID in its closure (9cb9dc94-2709-46a6-a8c2-de82e402652d) - The old location gets processed first, then the new one
Solutions
Option 1: Use
switchMapto Cancel Previous Requeststhis.route.params.pipe( takeUntil(this.ngUnsubscribe), switchMap(async params => { // Your parameter processing logic here if (environment.server.isAnonymous && StringHelper.isValidGUID(params['locationId'])) { await this.globalService.subLocations(true, true, [params['locationId']]); } this.isShowLoading = true; this.isChangingLocation = true; this.inputSearch.pageIndex = this.substancePageIndex = 0; this.setPaginator(0); return params; // Return params to continue the chain }), switchMap(params => { // Process location logic if (StringHelper.isValidGUID(params['locationId']) && params['locationId'] !== this.allText) { this.locationId = params['locationId']; this.inputSearch.locationIds = []; this.inputSearch.locationId = this.locationId; this.globalService.submitActiveLocation(this.locationId); this.globalService.setLocationIdToLocalStorage(this.locationId); return this.globalService.locationList$.pipe( switchMap(allLocation => { if (!this.checkLocationExisted(allLocation)) { this.router.navigate([this.isAnonymous ? '/not-permission' : '/substance/all']); return EMPTY; } return this.globalService.getLocationByIdNotIncludeChemicals(this.locationId, true); }) ); } else { // Handle other cases return of(null); } }) ).subscribe(locationDetail => { // Handle location detail if (locationDetail) { this.locationDetail = locationDetail; // Continue with your logic... } });Option 2: Flatten the Observable Chain
this.route.params.pipe( takeUntil(this.ngUnsubscribe), distinctUntilChanged((prev, curr) => prev['locationId'] === curr['locationId']), // Only emit when locationId actually changes switchMap(params => { // Reset state immediately this.isShowLoading = true; this.isChangingLocation = true; this.inputSearch.pageIndex = this.substancePageIndex = 0; this.setPaginator(0); if (StringHelper.isValidGUID(params['locationId']) && params['locationId'] !== this.allText) { this.locationId = params['locationId']; this.inputSearch.locationIds = []; this.inputSearch.locationId = this.locationId; this.globalService.submitActiveLocation(this.locationId); this.globalService.setLocationIdToLocalStorage(this.locationId); return combineLatest([ this.globalService.locationList$, this.globalService.getLocationByIdNotIncludeChemicals(this.locationId, true), this.globalService.echa_substances$, this.globalService.getChemicalDBConfigurationByNames([Constants.ExpiredSubstance, Constants.ConflictSubstanceWithSubstance, Constants.CheckMixturesChemicals]) ]).pipe( map(([allLocation, locationDetail, substanceFromECHAPIC, configs]) => ({ params, allLocation, locationDetail, substanceFromECHAPIC, configs })) ); } else { // Handle 'all' case this.locationId = null; this.locationDetail = null; this.inputSearch.locationId = null; return combineLatest([ this.globalService.locationList$, this.globalService.echa_substances$, this.globalService.getChemicalDBConfigurationByNames([Constants.ExpiredSubstance, Constants.ConflictSubstanceWithSubstance, Constants.CheckMixturesChemicals]) ]).pipe( map(([allLocation, substanceFromECHAPIC, configs]) => ({ params, allLocation, locationDetail: null, substanceFromECHAPIC, configs })) ); } }) ).subscribe(({ params, allLocation, locationDetail, substanceFromECHAPIC, configs }) => { // Process all data together this.allLocation = allLocation; this.listSubstanceFromECHAPIC = substanceFromECHAPIC; this.configExpiresYear = configs.find(config => config.name === Constants.ExpiredSubstance); this.showConflictChemicalAndChemical = configs.find(config => config.name === Constants.ConflictSubstanceWithSubstance)?.status; this.isCheckMixturesChemical = configs.find(config => config.name === Constants.CheckMixturesChemicals)?.status; if (locationDetail) { this.locationDetail = locationDetail; // Handle work assignment tab logic... } if (this.locationDetail && this.allLocation.filter(x => x.id == this.locationDetail?.id).length > 0) { this._initBreadcrumbData(); } });Why
setTimeoutWorksThe
setTimeoutworks because it delays the execution until the next tick of the event loop, allowing the previous observable chain to complete and clean up before starting the new one. However, this is a fragile solution that doesn't address the root cause.Recommended Approach
Use Option 2 with
switchMapanddistinctUntilChangedas it:- Cancels previous requests when new route params arrive
- Prevents duplicate processing of the same locationId
- Flattens the observable chain to avoid nested subscription timing issues
- Makes the code more maintainable and predictable
The key is using
switchMapinstead of nested subscriptions, which automatically cancels the previous inner observable when a new value arrives from the outer observable. - New route params arrive (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.