使用Angular FullCalendar遇TypeError: Cannot read property ‘map’ of undefined报错求助
Let's walk through the issues in your code and fix them one by one—there are two main culprits here causing the error and potential unexpected behavior:
1. The API response doesn’t have a data property (or it’s undefined)
Your error originates directly from this line in service.ts:
return response.json().data.map((data) => { ... });
When you call response.json().data, if your API’s response doesn’t include a top-level data field (or the response structure is different than you expected), data becomes undefined—and you can’t call .map() on undefined values.
Fix for this:
First, verify what your API actually returns. Open your browser’s DevTools > Network tab, trigger the request, and check the response body. Once you confirm the correct structure, adjust your code to handle cases where data might be missing:
getEvents() { return this.http.get('http:///api/lessons') .map(response => { const parsedResponse = response.json(); // Fallback to an empty array if data doesn't exist to avoid errors const lessonData = parsedResponse.data || []; return lessonData.map(data => ({ ...data, start: data.start_time })); }); }
2. Incorrect assignment of this.events in home.ts
Your current code does this:
this.events = this.service.getEvents().subscribe(events => {this.events = events;});
The subscribe() method returns a Subscription object, not the event data you’re expecting. So you’re first assigning a Subscription to this.events, then overwriting it inside the callback. This can break FullCalendar, as it expects an array of event objects.
Fix for this:
Remove the initial assignment and only set this.events inside the subscribe callback. Add error handling too, to catch API failures:
ngOnInit(){ this.service.getEvents().subscribe( events => { this.events = events; }, error => { console.error('Failed to load events:', error); } ); }
Extra Troubleshooting Tips
- Double-check your API URL:
http:///api/lessonshas an extra slash—make sure it’s a valid, complete URL (e.g.,http://localhost:3000/api/lessons). - Add
console.log(parsedResponse)inside themapoperator to inspect the exact structure of your API response, so you can adjust the mapping logic if needed.
内容的提问来源于stack exchange,提问作者B.T

