Angular组件出现TypeError: 无法读取未定义属性'process',求最佳实践
Hey there! Let's break down this error and get your component working smoothly.
What's Causing the Error?
The error Cannot read property 'process' of undefined tells us that when your code tries to access this.ProcessInfo.process, the this.ProcessInfo variable is either undefined or set to false (since you've typed it as any | false). If the variable isn't initialized properly or hasn't been populated with data yet, trying to dig into nested properties like process will throw this error.
Step-by-Step Solutions
1. Add Defensive Checks for Nested Properties
Use optional chaining (?.) to safely access nested properties without breaking if any layer is missing. This is a clean, modern way to avoid null/undefined errors in TypeScript:
// Replace this risky check if (this.ProcessInfo.process.data.mortgage.length) { // With this safe version if (this.ProcessInfo?.process?.data?.mortgage?.length) {
The optional chain operator stops evaluating and returns undefined if any part of the chain is null or undefined, preventing the TypeError entirely.
If you prefer explicit checks, you can also verify this.ProcessInfo exists first:
if (this.ProcessInfo && this.ProcessInfo.process?.data?.mortgage?.length) {
2. Initialize ProcessInfo Properly
Right now, ProcessInfo is declared but not initialized, so it starts as undefined. Give it a default value to avoid early errors:
// Initialize with an empty object (adjust based on your actual data structure) ProcessInfo: any | false = {};
For better type safety (and to catch bugs earlier), consider defining a proper interface instead of using any:
interface MortgageItem { mortgageHeader: { category: string } | null; } interface ProcessData { mortgage: MortgageItem[]; } interface Process { data: ProcessData; } ProcessInfo: Process | false = {} as Process;
3. Optimize Template Rendering
Calling showSaveItems() directly in *ngFor runs the function on every change detection cycle, which can hurt performance. Instead, store the result in a class variable and update it when ProcessInfo changes:
savedItems: Set<any> = new Set(); // Update savedItems when ProcessInfo is loaded (e.g., after an API call) this.savedItems = this.showSaveItems();
Then update your template to loop over the precomputed variable:
<li *ngFor="let item of savedItems"> <strong>{{ item.text }}</strong> </li>
4. Fix Unused Variable (Optional but Critical)
I noticed you're defining findItem but not using it—this means your typeCategory array will stay empty, and the returned Set won't have any items to display. Make sure to add the found item to typeCategory:
const findItem = this.categories.find( obj => obj.value == mortgageItem.mortgageHeader.category ); if (findItem) { this.typeCategory.push(findItem); }
Full Modified Code Example
myComponent.ts:
interface MortgageItem { mortgageHeader: { category: string } | null; } interface ProcessData { mortgage: MortgageItem[]; } interface Process { data: ProcessData; } ProcessInfo: Process | false = {} as Process; typeCategory: any[] = []; dataTypesLoop: any[] = []; dataTypes: Set<any> = new Set(); savedItems: Set<any> = new Set(); ngOnInit() { // Example: Load ProcessInfo from an API or service this.loadProcessInfo().then(info => { this.ProcessInfo = info; this.savedItems = this.showSaveItems(); }); } showSaveItems = () => { this.typeCategory = []; this.dataTypesLoop = []; if (this.ProcessInfo?.process?.data?.mortgage?.length) { for (const mortgageItem of this.ProcessInfo.process.data.mortgage) { if (mortgageItem.mortgageHeader !== null) { const findItem = this.categories.find( obj => obj.value == mortgageItem.mortgageHeader.category ); if (findItem) { this.typeCategory.push(findItem); } } } } this.dataTypes = new Set(this.dataTypesLoop); return new Set(this.typeCategory); };
myComponent.html:
<li *ngFor="let item of savedItems"> <strong>{{ item.text }}</strong> </li>
内容的提问来源于stack exchange,提问作者Azer Abbasov

