如何从角度4的 url 得到 param?

我正试图从 URL 获取开始日期。 URL 看起来像 http://sitename/booking?startdate=28-08-2017

我的代码如下:

aap.module.ts

    import {...};


@NgModule({
declarations: [
AppComponent, ModalComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
ReactiveFormsModule,
RouterModule.forRoot([{
path: '',
component: AppComponent
},
]),
],
providers: [ContactService, AddonService, MainService],
bootstrap: [AppComponent]
})
export class AppModule { }

组件

import {...}
import {Router, ActivatedRoute, Params} from '@angular/router';


constructor(private activatedRoute: ActivatedRoute) {
// subscribe to router event
this.activatedRoute.queryParams.subscribe((params: Params) => {
console.log(params);
});


}

但它给出了下面的错误

未经处理的承诺拒绝: 没有基础 href 设置。请提供一个值 用于 APP _ BASE _ HREF 标记或向文档添加基元素 Zone: ; Task: Promise.then ; Value: Error: No base href set. 请为 APP _ BASE _ HREF 令牌提供一个值或添加一个基 元素添加到文档中。

Angular 是怎么知道基地 href 的?

299461 次浏览

Update

我相信 Dimitry Grinko 在这篇文章中的回答比这个要好。

旧答案

这样应该可以从 url 中检索 params:

constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
let date = params['startdate'];
console.log(date); // Print the parameter to the console.
});
}

本地变量 date 现在应该包含来自 URL 的 开始日期参数。路由器和参数模块可以删除(如果没有在类的其他地方使用)。

路线

export const MyRoutes: Routes = [
{ path: '/items/:id', component: MyComponent }
]

组件

import { ActivatedRoute } from '@angular/router';
public id: string;


constructor(private route: ActivatedRoute) {}


ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
}
constructor(private activatedRoute: ActivatedRoute) {
}


ngOnInit() {
this.activatedRoute.params.subscribe(paramsId => {
this.id = paramsId.id;
console.log(this.id);
});
  

}

检查 URL 字符串中的参数或在 routeConfig 中作为 :param检查参数

Downstream. Component. ts

...
import {Router,ActivatedRoute} from '@angular/router';
...
export class DownstreamComponent  {
constructor(
private route: ActivatedRoute,
private router: Router
) {
if(this.route.snapshot.queryParams)
console.log(this.route.snapshot.params); // e.g. :param1 in routeConfig
if(this.route.snapshot.queryParamMap.get('param1'))
console.log(this.route.snapshot.queryParamMap.get('param1')); // e.g. in URI ?param1=blah
}


}

接受的答案使用可观察到的参数来检索,这个参数在整个组件生命周期的参数将发生变化时非常有用。

如果参数不变,可以考虑在路由器 URL 的快照上使用 Params对象。

snapshot.params返回对象中 URL 中的所有参数。

constructor(private route: ActivateRoute){}


ngOnInit() {
const allParams = this.route.snapshot.params // allParams is an object
const param1 = allParams.param1 // retrieve the parameter "param1"
}

使用 paramMap

这将提供参数名称及其值

//http://localhost:4200/categories/1
//{ path: 'categories/:category', component: CategoryComponent },


import { ActivatedRoute } from '@angular/router';


constructor(private route: ActivatedRoute) { }


ngOnInit() {


this.route.paramMap.subscribe(params => {
console.log(params)
})
}
import {Router, ActivatedRoute, Params} from '@angular/router';


constructor(private activatedRoute: ActivatedRoute) { }


ngOnInit() {
this.activatedRoute.paramMap
.subscribe( params => {
let id = +params.get('id');
console.log('id' + id);
console.log(params);




id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
}
)


}

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
let id = x.get('id');
console.log(id);
});

在角度上,他们把它分成两种 url。

  1. URL 模式 /heroes/:limit。示例: /heroes/20

    • You can get raw value by using route.snapshot.paramMap.get.
    • route.paramMap订阅获取 params
  2. URL 模式 /heroes。示例: /heroes?limit=20

    • 您可以使用 route.snapshot.queryParamMap获得原始值

Reference: 你只需要知道角度参数

Hope this helps someone. In case that u get undefined while doing this with something that's not "id", check if u are passing right parameter:

如果父组件. ts 中的路由是:

 onSelect(elem) {
this.router.navigateByUrl(`/element/${elem.type}`);
}

以及子组件中的

  type: string;
elem: ElemModel;


constructor(
private elemService: ElemService,
private route: ActivatedRoute
) {}


ngOnInit() {
this.route.params.subscribe((data) => {


console.log(data);  // 'data' will give u an object with the type inside, check the
name of that type inside console of devTool, as u will put that name inside
data[HERE] down below.


this.type = data["elem-type-maybe"]; // Don't do this.type = data["type"], do
data[NAME] as said above.


this.elem = this.elemService.getElem(this.type); // getElem is method in service
which returns that specific type.
});

请尝试获取起始日期从给定的预订 URL 路由参数:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';


@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {


constructor(private activeRoute: ActivatedRoute) {
this.activeRoute.queryParams.subscribe((qp) => {
console.log('Get Router Params:', this.activeRoute.snapshot.queryParams.startdate);
});
}


ngOnInit(): void {
}


}


For route URL related more information you can go through 给你

app.module.ts

import { Routes,RouterModule } from '@angular/router';


const routes: Routes = [
{
path: '',
component: HomeComponent
}
{
path: '/users/:id/:name',
component: UsersComponent
}
]


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

组件页

import { ActivatedRoute, Params } from '@angular/router';


export class UserComponent implements OnInit {
user : {id: number, name: string};


constructor(private route: ActivatedRoute) {}


ngOnInit() {
// If you get param one time in page use below code...
this.user = {
id : this.route.snapshot.params['id'],
name : this.route.snapshot.params['name']
};
// Dynamically change params use below code...
this.route.params.subscribe((param : Params) => {
this.user.id = param['id'];
this.user.name = param['name'];
});
}
}