我有三个子组件嵌套在父组件中。 我试图让它们在解决数据后独立显示。到目前为止,只有当所有结果都已获取数据时才会激活完整路径,这会导致所有子组件在相当长的一段时间后出现(某些API调用很长)。
以下是一些简化的代码:
路线:
const appRoutes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent,
children : [
{
path: 'cpt1',
component: Component1,
outlet: 'cpt1',
resolve: {
data: Cpt1Resolve
}
},
{
path: 'cpt2',
component: Component2,
outlet: 'cpt2',
resolve: {
data: Cpt2Resolve
}
},
{
path: 'cpt3',
component: Component3,
outlet: 'cpt3',
resolve: {
data: Cpt3Resolve
}
}
]
}
];
应用程序组件:
@Component({
selector: 'my-app',
template: `
<h1>Angular 2 Asynchronous loading of children components</h1>
<div>
<router-outlet></router-outlet>
</div>`
})
export class AppComponent {}
主页组件:
@Component({
selector: 'home-cpt',
template: `
<h2>You're on home</h2>
<router-outlet></router-outlet>
<router-outlet name="cpt1"></router-outlet>
<router-outlet name="cpt2"></router-outlet>
<router-outlet name="cpt3"></router-outlet>
`
})
export class HomeComponent {
constructor(router: Router) {
router.navigateByUrl('home/(cpt1:cpt1//cpt2:cpt2//cpt3:cpt3)');
}
}
最后是一个儿童组件及其决心:
// CHILD COMPONENT 1
@Component({
selector: 'cpt1',
template: `
<h3>Cpt1 displayed</h3>
`
})
export class Component1 implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit(): void {
this.route.data.forEach((data: any) => {
console.log('data cpt 1', data);
});
}
}
@Injectable()
export class Cpt1Resolve implements Resolve<any> {
constructor() {}
resolve (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return Observable.create((observer) => {
setTimeout(() => {
observer.next('Sample Text 1');
observer.complete();
}, 2000);
});
}
}
有没有办法强制路由器在收到数据后立即显示子组件? 我在这里做错了什么?
The complete plunker(等待它)
答案 0 :(得分:2)
似乎不幸的是,一旦解析器完成就不可能显示一个组件,并且有角度的人不打算改变它以使其成为可能。