When navigating between Account and Profile, the PeopleService is being called each time. You can also see the person's name and website details flicker.
Because the Account and Profile are children of PeopleComponent, and PeopleModule is the provider for the PeopleService, I'm expecting that the PeopleService to only be called when I first navigate to a Person, and for the person's details (name/website) not have to refresh (no flicker)
Here's a plunker: http://plnkr.co/edit/ZFEYYN45o1LaLsIpJwSK
PeopleModule:
import { NgModule } from '@angular/core';
import { PeopleService } from './people.service';
import { PeopleComponent } from './people.component';
import { peopleRouting } from './people.routes';
@NgModule({
imports: [
peopleRouting
],
declarations: [
PeopleComponent
],
providers: [
PeopleService
]
})
export class PeopleModule { }
PeopleRoutes:
import { Routes, RouterModule } from '@angular/router';
import { PeopleComponent } from './people.component';
const peopleRoutes: Routes = [
{
path: ':id',
component: PeopleComponent,
children: [
{
path: 'account',
loadChildren: 'app/accounts/accounts.module#AccountsModule'
},
{
path: 'profile',
loadChildren: 'app/profiles/profiles.module#ProfilesModule'
}
]
}
];
export const peopleRouting = RouterModule.forChild(peopleRoutes);
PeopleService
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class PeopleService {
constructor(
private _http: Http
) { }
get(id: number): Observable<any> {
console.info('person service called');
return this._http
.get(`http://jsonplaceholder.typicode.com/users/${id}`)
.map(response => response.json());
}
}
PeopleComponent
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PeopleService } from './people.service';
@Component({
template: `
<h2>
{{person?.name}} <br>
<small>{{person?.website}}</small>
</h2>
<nav>
<a routerLink="account" routerLinkActive="active">Account</a> |
<a routerLink="profile" routerLinkActive="active">Profile</a>
</nav>
<router-outlet></router-outlet>
`
})
export class PeopleComponent implements OnInit {
person;
constructor(
private _person: PeopleService,
private _route: ActivatedRoute
) { }
ngOnInit() {
this.getPerson();
}
getPerson() {
this._route.params.subscribe(params => {
let id = +params['id'];
this._person.get(id).subscribe(person => this.person = person);
})
}
}
Thanks for your help!