如何在父级数据更改时更新子路由中的数据
path: 'dashboard',
component: DashboardComponent,
resolve: {profileDetails: ProfileDetailsResolverService},
children: [
{
path: '',
component: DashboardHomeComponent,
pathMatch: 'full',
},
{
path: 'my-profile',
component: MyProfileComponent,
resolve: { profileDetails: ProfileDetailsResolverService }
},
{
path: 'web-development',
component: WebDevComponent,
},
]
}
];
在prolife组件中,用户可以更新其个人资料图片和所有其他详细信息,例如姓名。仪表板组件具有标题,该标题显示在所有子组件上。标头中包含名称和个人资料图片之类的内容,如果用户更改了此名称和个人资料图片,我将使用以下服务来更新DashboardComponent中的数据。
在个人资料组件中
if profile is changed() {
this.comService.updated.next(true);
}
在仪表板组件中
export class DashboardComponent implements OnInit, OnDestroy {
ngOnInit() {
//the communication service is triggered from profile component and so it
updates the data in the header.
this.comService.updateState.subscribe((r)=>{
if(r) {
this.auth.getUserProfile().subscribe((res: any)=>{
this.userDetail = res.data;
this.avatarUrl = this.data.siteLink()+this.userDetail.avatar;
});
}
});
}
}
现在,如果我使用路由器链接转到WebDevComponent,则可以在其中看到旧的配置文件数据。仅当我硬刷新页面时,数据才会更新。这就是我使用.parent
在WebDevComponent中获取数据的方式 export class WebDevComponent implements OnInit {
constructor(private auth: AuthService, private activeRoute:
ActivatedRoute,
private router: Router) {
activeRoute.data.subscribe((res)=> {
this.userDetail = res.profileDetails.data;
})
}
userDetails: any;
ngOnInit(){
this.activatedRoute.parent.data.subscribe((data: any)=>{
this.userDetails = data.profileDetails.data;
});
}
}
现在,如果我在WebDevComponent的路由中使用resolve: { profileDetails: ProfileDetailsResolverService }
而不是在父级使用this.activatedRoute.data.subscribe((data: any)
,那么该路由将更新数据,因为这将发送一个新的api请求并获取数据,但是无法发出另一个api /服务器请求。
答案 0 :(得分:1)
尝试将runGuardsAndResolvers:始终添加到子配置
path: 'dashboard',
component: DashboardComponent,
resolve: {profileDetails: ProfileDetailsResolverService},
runGuardsAndResolvers: 'always',
children: [
{
path: '',
component: DashboardHomeComponent,
runGuardsAndResolvers: 'always',
pathMatch: 'full',
},
{
path: 'my-profile',
component: MyProfileComponent,
runGuardsAndResolvers: 'always',
resolve: { profileDetails: ProfileDetailsResolverService }
},
{
path: 'web-development',
component: WebDevComponent,
runGuardsAndResolvers: 'always',
},
]
}
]
并添加onSameUrlNavigation ?:“重新加载”以路由Config
RouterModule.forRoot([.., {
onSameUrlNavigation: 'reload'
}) ]