ngOnInit(): void { this.featureInventoryProductsTableEnabled =…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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
Okay, let's break down this ngOnInit and the navigation issue.
The core problem stems from complex asynchronous operations and potential race conditions triggered by route changes within the ngOnInit lifecycle hook. The fact that setTimeout fixes it is a strong indicator of a timing issue.
Here's a breakdown of the code and the likely cause:
Code Analysis:
subUserProfile Subscription: This fetches the user profile. It correctly uses takeUntil(this.ngUnsubscribe).route.params Subscription (Nested): Crucially, the subscription to route parameter changes (route.params) happens inside the subUserProfile subscription. This means the parameter handling only starts after the user profile is obtained.route.params subscription, there's significant nesting:
if/else if/else block based on params['locationId'].if block (for a valid GUID):
this.locationId, inputSearch, etc.).globalService.locationList$ (Nested Subscription 1).
globalService.getLocationByIdNotIncludeChemicals(...) and subscribe to it (Nested Subscription 2).
locationDetail, handle WA counts, and set activeTab.combineLatest which subscribes to locationList$, echa_substances$, and configuration fetches (Nested Subscription 3).setTimeout Fix: This suggests that when you navigate, the sequence of operations doesn't complete correctly or in the expected order immediately. Delaying one of the asynchronous calls (like ) gives other operations or the browser rendering cycle time to catch up, resolving the issue temporarily.getLocationByIdNotIncludeChemicalsWhy is 9cb9dc94... called first?
params receiving the new ID (821490e7...) correctly.params observable emits. The code inside executes:
this.isShowLoading = true;this.isChangingLocation = true;this.locationId is set to the new ID (821490e7...).this.globalService.submitActiveLocation(this.locationId);this.globalService.setLocationIdToLocalStorage(this.locationId);globalService.locationList$.globalService.getLocationByIdNotIncludeChemicals(this.locationId, true). This call uses the new ID.locationList$ subscription (or the combineLatest subscription to it) is still processing data related to the old location when the new fetch starts.takeUntil isn't clearing it fast enough, or a previous observable chain is still active.checkLocationExisted check might be evaluating against a locationList$ that hasn't updated yet or is momentarily inconsistent.Root Cause: The primary issue is the overly nested subscription structure. This makes the code hard to follow and prone to race conditions when the input (route.params) changes quickly. Specifically, subscribing to locationList$ inside the route.params handler, and then again inside combineLatest, is redundant and potentially problematic.
How to Fix (Refactoring Strategy):
The goal is to flatten the structure, use operators like switchMap and tap effectively, and ensure only necessary subscriptions are active.
switchMap: Since you want to react to the latest locationId and cancel any pending operations for the previous location, switchMap is the ideal operator for the route.params subscription.switchMap, concatMap, tap) instead of nesting subscriptions within subscriptions.isShowLoading, isChangingLocation, locationId, locationDetail, etc.) are updated logically within the observable chain.Refactored Example (Conceptual):
import { of, combineLatest, EMPTY, Subject } from 'rxjs';
import { switchMap, takeUntil, tap, catchError, map } from 'rxjs/operators';
// ... other imports
export class YourComponent implements OnInit, OnDestroy {
// ... existing properties ...
private ngUnsubscribe = new Subject<void>(); // Ensure this is initialized
ngOnInit(): void {
// Initial setup that doesn't depend on route params or user profile immediately
this.featureInventoryProductsTableEnabled = checkFeatureFlag(SubstanceFeatureFlag.LIST_INVENTORY_MODE);
this.isShowLoading = true;
this.localeString = this.cookieHelper.getStore('languageCulture');
this._listeningEvent();
this._checkPermission();
this._getCompanyProfile();
this.checkDevice();
if (this.featureInventoryProductsTableEnabled) {
this.loadFontFamily();
}
// Chain dependent operations using switchMap
this.globalService.subUserProfile().pipe(
takeUntil(this.ngUnsubscribe),
switchMap(userProfile => {
// Set userId and load initial preferences once user profile is available
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);
}
// IMPORTANT: Return the observable we want to chain next
return this.route.params;
}),
switchMap(params => {
// This switchMap automatically cancels previous route param processing if a new one arrives quickly
console.log(params, 'params');
this.handleRouteChange(params); // Delegate handling to a method
// Return the observable for the actual data fetching logic
return this.processLocationData(params['locationId']);
}),
catchError(error => {
// Handle errors in the main chain (e.g., profile fetch, initial route param)
console.error("Error during initial setup or profile fetch:", error);
this.isShowLoading = false;
return EMPTY; // Stop processing
})
).subscribe({
// Use next, error, complete callbacks for clarity
next: (data) => {
// Data from processLocationData might arrive here if needed,
// but most state updates happen via tap within processLocationData
// console.log('Data processed:', data);
},
error: (err) => {
console.error("Subscription error:", err);
this.isShowLoading = false; // Ensure loading is off on error
this.isChangingLocation = false;
},
complete: () => {
// console.log("Initialization sequence complete.");
// Set loading state based on whether data fetching is truly finished
// This might need adjustment depending on how processLocationData signals completion
this.isShowLoading = false;
this.isChangingLocation = false;
}
});
}
// Separate method to handle route param changes and state resets
private handleRouteChange(params: any): void {
// Reset state related to location changes
this.isShowLoading = true;
this.isChangingLocation = true;
this.inputSearch.pageIndex = this.substancePageIndex = 0;
this.setPaginator(0);
}
// Method to encapsulate the location data fetching logic
private processLocationData(locationIdParam: string) {
// Anonymous check (handle side effects carefully)
if (environment.server.isAnonymous && StringHelper.isValidGUID(locationIdParam)) {
this.globalService.subLocations(true, true, [locationIdParam]).subscribe(); // Consider side-effect handling
}
// Logic based on locationId
if (StringHelper.isValidGUID(locationIdParam) && locationIdParam !== this.allText) {
this.locationId = locationIdParam;
console.log(this.locationId, 'locationId 111');
this.inputSearch.locationIds = [];
this.inputSearch.locationId = this.locationId;
this.globalService.submitActiveLocation(this.locationId);
this.globalService.setLocationIdToLocalStorage(this.locationId);
// Use concatMap to ensure sequential fetching: Location Detail -> Other Data
return this.globalService.getLocationByIdNotIncludeChemicals(this.locationId, true).pipe(
switchMap(locationDetail => { // Use switchMap here too if locationDetail fetch could be cancelled
if (!locationDetail) {
console.warn(`Location detail not found for ID: ${this.locationId}`);
// Handle case where location not found appropriately, maybe return EMPTY or trigger navigation
// Trigger navigation if required: return from(this.router.navigate(...));
return EMPTY;
}
locationDetail.locationAttribute = locationDetail.locationAttribute || [];
this.locationDetail = locationDetail;
console.log(this.locationDetail, 'locationDetail');
// Prepare observables for data needed concurrently
let waCountObservable = of(null); // Default empty observable
if (this.isShowWATab) {
const request = new GetCountWorkAssignmentInLocationRequest();
request.locationId = this.locationId;
waCountObservable = this.waService.getCountWorkAssignmentInLocation(request).pipe(
catchError(err => {
console.error("Error fetching WA count:", err);
return of(null); // Return null on error to not break combineLatest
})
);
}
// Fetch configurations and location list concurrently
const configsObservable = this.globalService.getChemicalDBConfigurationByNames([
Constants.ExpiredSubstance,
Constants.ConflictSubstanceWithSubstance,
Constants.CheckMixturesChemicals
]);
// Combine results
return combineLatest([
this.globalService.locationList$, // Assumes this is a BehaviorSubject/ReplaySubject
this.globalService.echa_substances$,
configsObservable,
waCountObservable
]).pipe(
tap(([allLocation, substanceFromECHAPIC, configs, waCountResult]) => {
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;
// Set active tab based on WA count result and preferences
const lastActivedTab = localStorage.getItem(`${this.userId}${Constants.localStorageKey.LAST_ACTIVED_TAB}`);
if (this.isShowWATab) {
this.isDisableWATab = !waCountResult; // Set disable state based on fetched count
this.activeTab = this.isDisableWATab ? this.activeSubstanceTab.id : (lastActivedTab ? +lastActivedTab : this.activeSubstanceTab.id);
} else {
this.activeTab = lastActivedTab ? +lastActivedTab : this.activeSubstanceTab.id;
}
// Check location existence for breadcrumbs AFTER getting allLocation
if (this.locationDetail && this.allLocation.filter(x => x.id === this.locationDetail?.id).length > 0) {
this._initBreadcrumbData();
}
// Data fetching complete for this location
this.isShowLoading = false;
this.isChangingLocation = false;
}),
catchError(error => {
console.error("Error in combineLatest chain:", error);
this.isShowLoading = false;
this.isChangingLocation = false;
return EMPTY;
})
);
}),
catchError(error => {
console.error(`Error fetching location detail for ${this.locationId}:`, error);
// Maybe navigate away or show error message
this.isShowLoading = false;
this.isChangingLocation = false;
// Consider navigating to a safe page like '/substance/all' or '/not-found'
// return from(this.router.navigate(['/substance/all']));
return EMPTY;
})
);
} else if (locationIdParam !== this.allText) {
// Invalid location ID or specific non-GUID format, navigate away
console.log(`Invalid or non-all locationId: ${locationIdParam}. Navigating away.`);
this.router.navigate([this.isAnonymous ? '/not-permission' : '/substance/all']);
return EMPTY; // Stop the chain
} else {
// Handle the case where locationId is 'all' or null/undefined
this.locationId = null;
this.locationDetail = null;
this.inputSearch.locationId = null;
// Fetch configurations etc. for the 'all' view
const configsObservable = this.globalService.getChemicalDBConfigurationByNames([
Constants.ExpiredSubstance,
Constants.ConflictSubstanceWithSubstance,
Constants.CheckMixturesChemicals
]);
return combineLatest([
this.globalService.locationList$,
this.globalService.echa_substances$,
configsObservable
]).pipe(
tap(([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;
// No specific location detail, breadcrumb logic might differ or be skipped
// Maybe reset breadcrumbs if necessary: this.breadcrumbService.reset();
this.isShowLoading = false;
this.isChangingLocation = false;
}),
catchError(error => {
console.error("Error fetching configs for 'all' location:", error);
this.isShowLoading = false;
this.isChangingLocation = false;
return EMPTY;
})
);
}
}
ngOnDestroy(): void {
// Ensure subscriptions are cleaned up
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
Explanation of Changes:
ngUnsubscribe: Make sure you have private ngUnsubscribe = new Subject<void>(); and implement OnDestroy to call this.ngUnsubscribe.next(); this.ngUnsubscribe.complete();.switchMap: Used twice. The first switches from subUserProfile to route.params. The second switches from route.params to the actual data fetching logic (processLocationData). This ensures that if you navigate again while the previous data is still loading, the previous request is automatically cancelled.processLocationData Method: Encapsulates the logic for handling a specific locationId change. This makes ngOnInit cleaner.switchMap (or could use concatMap if strict order is mandatory) for getLocationByIdNotIncludeChemicals to ensure it's called after other state updates for the new location are set.combineLatest is used correctly to fetch related data (location list, ECHA data, configs, WA count) concurrently after the primary location detail is fetched.tap Operator: Used to perform side effects (like setting component properties this.allLocation = ..., this.locationDetail = ..., etc.) within the observable chain without altering the stream's data emission.catchError is added at various stages to prevent the entire chain from breaking and to ensure loading states are reset. EMPTY is returned from catchError or invalid paths to terminate that specific observable chain gracefully.isShowLoading flag is managed more explicitly within the chain, ensuring it's turned off upon completion or error.This refactored approach should resolve the timing issues and make the component initialization more robust and easier to maintain.