【问题标题】:Read route params from directly entered url in app从应用程序中直接输入的 url 读取路由参数
【发布时间】:2018-07-11 20:11:50
【问题描述】:

我的问题是关于 angular 4,如何获取路由参数,例如,如果用户使用而不是默认 url(例如 http://localhost:3000/)进入您的页面,而不是像 http://localhost:3000/user/:id 这样的东西,以及能够从该网址获取:id(用户直接在浏览器中输入,而不是通过应用程序导航)。

在下面的示例中使用了相同的组件,主要是因为需要捕获该 id 并调度其他操作,如果它存在,那就是它。

我尝试过使用ActivatedRoute,但据我所知,这仅在整个应用程序中导航时有效,从应用程序内部,而不是在这种情况下,如果该 url 总是返回一个空值直接在浏览器中输入,它会被重定向到默认的/ 路由,就是这样。

非常感谢任何提示或指示

app.routing-module.ts

import {hookComponent} from './hook.component';
import {RouterModule, Routes} from '@angular/router';
import {NgModule} from '@angular/core';

export const routes: Routes = [
  {
    path: '',
    component: HookComponent
  },
  {
    path: 'user/:id',
    component: HookComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { enableTracing: true })],
  exports: [RouterModule]
})
export class AppRoutingModule {}

钩子组件

import {Component, EventEmitter, Input, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, ParamMap} from '@angular/router';

@Component({
  selector: 'hook',
  templateUrl: 'hook.component.html',
  styleUrls: ['hook.component.scss']
})
export class HookComponent implements OnDestroy, OnInit {
  constructor(private route: ActivatedRoute) {
    
  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       console.log('params are', params); //null?
    });

  }
}

【问题讨论】:

  • 将 RouteModule.forRoot() 直接导入 app.module 时会发生什么?
  • 好吧,没什么,只是直接从那里使用路线,没有注意到任何问题或其他问题,应用程序本身比所提供的示例大得多,并且运行良好:)跨度>

标签: javascript angular angular4-router


【解决方案1】:

通过Location访问当前url

public  constructor(location:Location) {
  let url = location.prepareExternalUrl(location.path());
}

并从中解析出id

【讨论】:

  • 感谢您的提示,但仍然没有运气,只返回基本 url /,而不是匹配的路径
【解决方案2】:

你的方式已经可以了,但是在你的例子中params是一个数组,你可以通过调用params['id']来访问:id

this.sub = this.route.params.subscribe(params => {
  console.log('params are', params['id']);
});

Here 是 stackblitz 上的一个工作示例。

【讨论】:

  • 是的,现在似乎可以工作了,需要进一步挖掘,感谢您的帮助,并且演示,非常感谢它,这样让事情变得更容易:)
【解决方案3】:

如果您只想记录params.id;尝试像这样使用ActivatedRouteSnapshot

  ngOnInit() {
    console.log(this.route.snapshot.params.id);
}

如果您想检查 params.id 是否存在,可以执行以下操作:

import {Component, EventEmitter, Input, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, ParamMap} from '@angular/router';

@Component({
  selector: 'hook',
  templateUrl: 'hook.component.html',
  styleUrls: ['hook.component.scss']
})
export class HookComponent implements OnDestroy, OnInit {

  hasId: boolean = false;
  constructor(private route: ActivatedRoute) {

  }

  ngOnInit() {
    if(this.route.snapshot.params.id !== null)
    {
        // do magic....
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多