Cannot navigate same route in Angular

女生的网名这么多〃 提交于 2019-12-08 14:03:33

问题


I have a List and Details component in my Angular 7 project and I can open the details of a record by clicking the link on the List page. However, if I refresh on the same Details page or open the same Details page via hyperlink (e.g. opening the same record on the List in a new tab), HTTP Error 404.0 - Not Found is encountered. My code is as shown below:

routing.module.ts:

const routes: Routes = [
    {
        path: 'user',    
        component: UserPanelComponent

        children: [
            {
                path: 'dashboard',
                component: UserDashboardComponent
            },
            {
                path: 'issue/detail/:id',
                component: IssueDetailComponent
            }
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})


list.component.html:

<a [routerLink]="['/user/issue/detail/', row.Id]">{{ row.Title }</a>


details.component.ts:

export class DetailComponent {

    constructor(private router: Router,
        public route: ActivatedRoute) {
        super();

        this.id = this.router.getCurrentNavigation().extras.state.id; //get id
    }

    ngOnInit(): void {

        /* I also try to use the following method in order to get id value. Both works, 
        but when refrehing page the code does not hit constructor or ngOninit blocks  */

        this.id = +this.route.snapshot.paramMap.get('id'); //get id

        this.loadDetails();
    }

    loadDetails() {
        if (this.id) {
            // load details
        }
    }
}

The stange thing is that when I click a record on the List component, the id parameter is passed and corresponding record is opened on the Details page. But when I right click on the same record and open it in a new tab OR refresh the page on Details page, HTTP Error 404.0 - Not Found error is encountered. I have tried to apply many suggestions bıt none of them worked. Any idea to fix this issue?


回答1:


Do you have this behaviour in both local and production environment ?

If you have a HTTP404 maybe it's not linked to angular. I had the same thing when packaging an angular app inside a WAR or JAR with spring boot for executing on an application server. If you do, (and if I remenber well) I had to add this configuration :

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**/*").addResourceLocations("classpath:/static/").resourceChain(true).addResolver(new PathResourceResolver() {

            @Override
            protected Resource getResource(String resourcePath, Resource location) throws IOException {
                Resource requestedResource = location.createRelative(resourcePath);
                return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/static/index.html");
            }
        });
    }
}

I don't think it will change something, but you can also try this to get the ID :

ngOnInit() {
    this.route.params.subscribe(params => {
        console.log("this is my id:"+params['id']);
    });
}



回答2:


If the component is opened using a button, hyperlink (e.g. /user/issue/detail?id=100) or the same page should be loaded with the same route parameters, the following approach can be used:

In this example record details is opened on the Details page by clicking on the List page or via an hyperlink of a button in an email message. On the other hand, the record is reloaded on refreshing page.

list-component.html:

<a [routerLink]="['/user/detail/']" [queryParams]="{ id: row.Id }">{{ row.Title }}</a>


details-component.ts:

this.id = +this.route.snapshot.queryParamMap.get("id"); 
//"+" sign converts string to number as the url parameter is string


routing-module.ts:

{ path: 'user/detail', component: DetailComponent },
{ path: 'user/detail/:id', component: DetailComponent },

The page can be loaded via button and hyperlink also:

<a href="http://../detail?id=216" target="_blank" >Comment</a>


来源:https://stackoverflow.com/questions/56559158/cannot-navigate-same-route-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!