在帐户和个人资料之间导航时,每次都会调用PeopleService。您还可以看到此人的姓名和网站详细信息闪烁。
因为Account和Profile是PeopleComponent的子代,而PeopleModule是PeopleService的提供者,所以我希望只有在我第一次导航到Person时才会调用PeopleService,以及该人员的详细信息(名称/网站) )不必刷新(没有闪烁)
这是一个掠夺者: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);
})
}
}
感谢您的帮助!
答案 0 :(得分:1)
这是Angular中的一个错误,应该在下一个版本中修复,如此处所述,
https://github.com/angular/angular/issues/10814
https://github.com/angular/angular/pull/10707
import { PeopleModule } from './people/people.module';
@NgModule({
imports: [
...
PeopleModule,
...
})
将Plunker更新为不使用延迟加载的模块,它可以正常工作!!
干杯!!