Angular 5 router.navigate does not work

六月ゝ 毕业季﹏ 提交于 2021-01-22 10:37:10

问题


I'm trying to redirect a user to another page based on some condition. Here's my example login component:

  ngOnInit() {
    console.log(">>> router", this.router)
    console.log(">>> activatedRoute", this.activatedRoute)

    if (this.activatedRoute.queryParams['value'].param === 'value') {
      console.log(">>> redirecting")
      this.router.navigate(['home']);
    }
  }

If I navigate to the login component without a parameter, then I'm shown the login component template, that's good.

However, when I navigate to the login component with a parameter named param and the value of value, then I want to redirect the user to the home page. That's not working.

Here's my home page route:

import { NgModule } from '@angular/core';

import { HomeComponent } from './home.component';
import { RouterModule, Routes } from '@angular/router';

const thisRoute: Routes = [
  {
    path: 'home',
    component: HomeComponent
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(thisRoute, {
      useHash: true, initialNavigation: false
    })
  ],
  declarations: [
    HomeComponent
  ]
})
export class HomeModule { }

I've created a test project in github for you to download and run on your computer. Just download this project: https://github.com/wvary/route-test

Run npm install.

Then run npm run start.

Navigate to http://localhost:8080/#/home

You should see something like:

You can see the content of each page by click on the three links. The idea is to be on the home page when you click on the middle link.

Thanks


回答1:


queryParams is Observable, so you cannot get parameters from it in this way. Another thing here to note is that queryParams was replaced in this version of Angular by queryParamMap.

Here is described how to using it properly.




回答2:


Try this this.router.navigate(['../home']);




回答3:


Try this please:

const thisRoute: Routes = [
  {
    path: 'home',
    component: HomeComponent
  }
];
export const routing = RouterModule.forRoot(thisRoute);

@NgModule({
  imports: [
   routing
    })
  ],
  declarations: [
    HomeComponent
  ]
})


来源:https://stackoverflow.com/questions/49701587/angular-5-router-navigate-does-not-work

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