Angular 5.2.0:ngZone.run中出现Cannot read property of undefined错误
Hey there! Let's work through your problem step by step since you're new to Angular—we'll get this sorted out clearly.
Core Problem: d is Null/Undefined
The main culprit here is your BehaviorSubject starts with an initial value of null. When you subscribe to resultObeservable$, it immediately emits that null value before your API call returns the actual ResultObject. That's why you're hitting the "d is null/undefined" error when trying to access d.resultDate.
Fix 1: Guard Against Null in the Subscription
You can add a simple check to only proceed when d exists:
this.resultObeservable$.subscribe(d => { if (d) { // Skip the initial null emission console.log(d); this.myCustomDate = d.myCustomDate; // Use your actual date property name here } });
Fix 2: Filter Nulls in the Observable Pipe (Cleaner Approach)
A better practice is to filter out null values upstream, so your subscription never has to handle them. Update your observable setup:
// Replace your existing resultObeservable$ definition this.resultObeservable$ = this.result$.pipe( filter(r => r !== null), // Ignore the initial null value map(r => r) // This map is optional if you don't need to transform the data ); // Now your subscription can safely access d without checks this.resultObeservable$.subscribe(d => { console.log(d); this.myCustomDate = d.myCustomDate; });
About ngZone.run()
Good news—you don't need it here! Angular's built-in HttpClient automatically runs API responses within Angular's zone, which means change detection will trigger normally when you update myCustomDate. You can remove the ngZone.run() wrapper entirely to simplify your code.
Bonus: Use the Async Pipe (Perfect for Beginners)
As a new Angular developer, the async pipe is a game-changer—it handles subscriptions for you and prevents memory leaks. You can bind your observable directly to the Kendo Date Picker in the template:
- Keep your filtered observable:
this.resultObeservable$ = this.result$.pipe( filter(r => r !== null) );
- In your template:
<kendo-datepicker [value]="(resultObeservable$ | async)?.myCustomDate" (valueChange)="onDateChange($event)" ></kendo-datepicker>
The ?. optional chaining operator ensures no errors are thrown while waiting for the API response.
Quick Recap
- Your
result$BehaviorSubject correctly emits the API result once fetched - Adding
filter(r => r !== null)eliminates the initial null emission causing your error ngZone.run()is unnecessary for HttpClient calls- The async pipe simplifies template binding and avoids manual subscription management
Hopefully this clears up your issues and helps you get that date showing in your Kendo Date Picker smoothly!
内容的提问来源于stack exchange,提问作者alaa_sayegh

