I'm currently developing an angular application that utilizes the Router to navigate between multiple components starting from AppComponent
. In order to demonstrate the issue I am facing, I have created a simplified version on plunker (Interestingly, the code runs without any problems locally but encounters issues on plunker.)
When the application is accessed from either http://localhost:3000
or http://localhost:3000/home
, everything works as intended when clicking on the links fruit1
and fruit2
which correctly changes the URL to http://localhost:3000/fruit/1
with the corresponding description text. However, the problem arises when directly accessing the URL http://localhost:3000/fruit/1
(typing it in the browser and hitting enter), it appears that the service call within the ngOnInit
of the fruit-detail.component.ts
occurs AFTER attempting to render the HTML component, resulting in the following stack trace:
EXCEPTION: TypeError: Cannot read property 'description' of null in [ desc: {{fruit.description}} in FruitDetailComponent@1:6]
angular2.dev.js:23925 EXCEPTION: TypeError: Cannot read property 'description' of null in [ desc: {{fruit.description}} in FruitDetailComponent@1:6]BrowserDomAdapter.logError @ angular2.dev.js:23925BrowserDomAdapter.logGroup @ angular2.dev.js:23936ExceptionHandler.call @ angular2.dev.js:1320(anonymous function) @ angular2.dev.js:12857schedulerFn @ angular2.dev.js:13264SafeSubscriber.__tryOrUnsub @ Rx.js:10775SafeSubscriber.next @ Rx.js:10730Subscriber._next @ Rx.js:10690Subscriber.next @ Rx.js:10667Subject._finalNext @ Rx.js:11191Subject._next @ Rx.js:11183Subject.next @ Rx.js:11142EventEmitter.emit @ angular2.dev.js:13245NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ angular2.dev.js:13666NgZoneImpl.inner.inner.fork.onHandleError @ angular2.dev.js:2143ZoneDelegate.handleError @ angular2-polyfills.js:394Zone.runGuarded @ angular2-polyfills.js:300NgZoneImpl.runInner @ angular2.dev.js:2155NgZone.run @ angular2.dev.js:13749(anonymous...
and so on...
<p>Subsequently, the console logs the message "got fruit inside fruitComponent !apple", reinforcing my suspicion that ngOnInit is called after rendering. How can I ensure that the app functions properly even when directly loading from the 'fruit/1' URL? Any assistance would be greatly appreciated. Thank you!</p>
<pre><code>===== extract data called!!
fruit-detail.component.ts:25 got fruit inside fruitComponent !apple