Angular 5 router.navigate无法正常工作 [英] Angular 5 router.navigate does not work

查看:217
本文介绍了Angular 5 router.navigate无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据某种条件将用户重定向到另一个页面.这是我的示例登录组件:

  ngOnInit(){console.log(>>路由器",this.router)console.log(>>> ActivatedRoute",this.activatedRoute)如果(this.activatedRoute.queryParams ['value'].param ==='value'){console.log(>>>重定向")this.router.navigate(['home']);}} 

如果我导航到不带参数的登录组件,那么将显示登录组件模板,这很好.

但是,当我使用名为param的参数和value的值导航到登录组件时,我想将用户重定向到主页.那是行不通的.

这是我的首页路线:

 从'@ angular/core'导入{NgModule};从'./home.component'导入{HomeComponent};从'@ angular/router'导入{RouterModule,Routes};const thisRoute:路线= [{路径:家",组件:HomeComponent}];@NgModule({进口:[RouterModule.forRoot(thisRoute,{useHash:true,initialNavigation:false})],声明:[家庭组件]})导出类HomeModule {} 

我已经在github中创建了一个测试项目,供您下载并在计算机上运行.只需下载此项目:

通过单击三个链接,您可以查看每个页面的内容.当您单击中间链接时,该想法将显示在主页上.

谢谢

解决方案

queryParams是可观察的,因此您无法以这种方式从中获取参数.这里要注意的另一件事是,在此版本的Angular中,queryParams已由queryParamMap取代.

此处介绍了如何正确使用它.

>

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

解决方案

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.

这篇关于Angular 5 router.navigate无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆