I'm a little bit new in Angular:
When I load my Angular application (Angular 4), a specific component's ngOnInit() method called even if it wasn't rendered. After I navigate my app to a route that renders this component, the ngOnInit() called again. Why is that? Is this some kind of error, or is this how it works? There is no error in the console.
(Because of this, in my component's ngOninit() a subscribe method runs twice.)
Update:
offer-info.component.ts:
import { Component, Input, OnInit, NgZone } from '@angular/core';
import { OfferService } from './offer.service';
import { Offer } from '../models';
declare var $: any;
@Component({
moduleId: module.id,
selector: 's2a-offer-info',
templateUrl: './offer-info.component.html',
})
export class OfferInfoComponent implements OnInit {
private zone: NgZone;
offer: Offer = null;
constructor(
private offerService: OfferService,
) { }
ngOnInit() {
//This is where I get two 'test' output on the console:
console.log('test');
this.zone = new NgZone({enableLongStackTrace: true});
this.offerService.getOfferForOfferInfo().subscribe((offer: Offer) => {
if (offer !== null) {
this.zone.run(() => {
this.offer = offer;
$('#s2aOfferInfoModal').modal();
});
}
});
}
}
In page-packages.component.html:
...
<!-- This tag appers only once in the whole application: -->
<s2a-offer-info></s2a-offer-info>
...
In app-routing.module.ts:
...
{ path: 'packages', component: PagePackagesComponent, canActivate: [LoggedInGuard] },
{ path: 'search', component: PageSearchComponent, canActivate: [LoggedInGuard] },
{ path: '', redirectTo: '/search', pathMatch: 'full' },
...