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 encountering seems to be related to the timing of the route parameter changes and the asynchronous operations that follow. When you navigate from one location to another, the route parameters are updated, and the
ngOnInitmethod is called again. However, the asynchronous operations (like fetching data from the server) might not complete in the expected order, leading to the old location ID being processed first.Here are a few potential reasons and solutions to address this issue:
Potential Reasons
- Asynchronous Operations: The asynchronous operations (like
getLocationByIdNotIncludeChemicals) might not complete in the expected order due to the nature of asynchronous code. - Route Parameter Changes: The route parameters might be changing rapidly, causing the old parameters to be processed first.
- State Management: The state of the component might not be reset properly between navigation changes.
Solutions
-
Use
ngOnDestroyto Clean Up Subscriptions: Ensure that all subscriptions are properly cleaned up when the component is destroyed to avoid stale data. -
Use
ngOnChangesfor Route Parameter Changes: If you're using Angular's router, you might want to usengOnChangesto react to route parameter changes more reliably. -
Debounce Route Parameter Changes: You can debounce the route parameter changes to ensure that the latest parameters are processed.
-
Use
setTimeoutas a Temporary Fix: While not ideal, usingsetTimeoutcan sometimes work as a temporary fix to ensure that the latest parameters are processed. However, this is not a robust solution and should be avoided in production code.
Example Solution Using
ngOnChangesIf you're using Angular's router, you can use
ngOnChangesto react to route parameter changes more reliably.import { Component, OnInit, OnDestroy, OnChanges, SimpleChanges } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subscription, takeUntil } from 'rxjs'; import { Subject } from 'rxjs'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit, OnDestroy, OnChanges { private ngUnsubscribe = new Subject<void>(); private routeSubscription: Subscription; constructor(private route: ActivatedRoute, private globalService: GlobalService) {} ngOnInit(): void { this.routeSubscription = this.route.params.pipe(takeUntil(this.ngUnsubscribe)).subscribe(params => { this.handleRouteParams(params); }); } ngOnChanges(changes: SimpleChanges): void { if (changes['locationId']) { this.handleRouteParams(changes['locationId'].currentValue); } } ngOnDestroy(): void { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } } handleRouteParams(params: any): void { if (StringHelper.isValidGUID(params['locationId'])) { this.globalService.getLocationByIdNotIncludeChemicals(params['locationId'], true).pipe(takeUntil(this.ngUnsubscribe)).subscribe((locationDetail) => { // Handle location detail }, (error) => { console.error(error); }); } } }Example Solution Using Debounce
You can use a debounce strategy to ensure that the latest parameters are processed.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subscription, takeUntil, debounceTime } from 'rxjs'; import { Subject } from 'rxjs'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit, OnDestroy { private ngUnsubscribe = new Subject<void>(); private routeSubscription: Subscription; constructor(private route: ActivatedRoute, private globalService: GlobalService) {} ngOnInit(): void { this.routeSubscription = this.route.params.pipe( takeUntil(this.ngUnsubscribe), debounceTime(300) // Adjust the debounce time as needed ).subscribe(params => { this.handleRouteParams(params); }); } ngOnDestroy(): void { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } } handleRouteParams(params: any): void { if (StringHelper.isValidGUID(params['locationId'])) { this.globalService.getLocationByIdNotIncludeChemicals(params['locationId'], true).pipe(takeUntil(this.ngUnsubscribe)).subscribe((locationDetail) => { // Handle location detail }, (error) => { console.error(error); }); } } }By using
ngOnChangesor debouncing the route parameter changes, you can ensure that the latest parameters are processed correctly, avoiding the issue of the old location ID being processed first.- Asynchronous Operations: The asynchronous operations (like
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.