angular - Angular 6/7 Getting Data from API When Returning to Previously Viewed Route
问题描述
I'm new to angular and having a bit of trouble. I want to direct a user to a data entry page where many of the fields are already filled by an api call to the database, by record id. The user will then edit some of those fields, save the data, and carry on. This is all working fine. The problem is that if the user goes off to a different page and does something else, then navigates back to that same URL where they did the initial data entry, the data shown on the page is the data that was originally fetched, not the data that was posted. I have a router set up, and a resolver to delay loading the page until all the data has been fetched from the api, but the api only seems to get called once, instead of each time the page is loaded.
My resolver:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ProjectVM> {
let id = route.paramMap.get('id');
return this.apiService.getProject(id).pipe(
take(1),
map(projectVM => {
if (projectVM) {
return projectVM;
} else {
this.router.navigate(['/projects']);
return null;
}
}))
}
My component:
ngOnInit(): void {
this.route.data.subscribe((data: { projectVM: ProjectVM }) => {
this.projectVM = data.projectVM;
});
}
Routing Module:
const routes: Routes = [
{ path: '', redirectTo: '/projects', pathMatch: 'full', runGuardsAndResolvers: 'always' },
{ path: 'projects', component: MyProjectsComponent },
{ path: 'project/:id', component: ProjectOverviewComponent, runGuardsAndResolvers: 'always', resolve: { projectVM: ProjectResolver } },
];
@NgModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' },
ProjectResolver,
LeaseResolver,
ProjectSearchResolver,
LeaseSearchResolver
]
})
export class AppRoutingModule { }
The data is posting to the database just fine, but the router doesn't seem to want to call the database more than once per ID.
解决方案
Can you please show in stackblitz. Btw ngOnInit is only called during component initialization. So if you are on same component ngOnInit won't be called.
推荐阅读
- python - 在 OpenMaya 中获取顶点法线?
- android - 我怎样才能获得像 ColorOs、Flyme、LineageOS 等 Android 类型?
- react-native - 反应原生 | 钩子组件
- python - 如何基于单列将数据框着色为在整行中具有相同颜色的条件热图
- android - 使用 OnBackPressedDispatcher() 的 OnBackPressedCallback() 不起作用
- python - 从 Pandas 数据透视表框架中注释数据点
- shopware - Shopware 6 在店面搜索中包含属性
- ios - iPad Safari Ctrl+C 类似 Enter 的操作
- python - 构建后无法导入 caffe
- docker - 我需要使用我的 D 盘来运行我的 Docker。我能怎么做?