首页 > 解决方案 > 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.

标签: angularangular-routingangular-router

解决方案


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.


推荐阅读