如何从角度4的URL中获取参数? [英] How to get param from url in angular 4?

查看:87
本文介绍了如何从角度4的URL中获取参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从URL获取开始日期. 该网址看起来像http://sitename/booking?startdate=28-08-2017

I'm trying to get startdate from the URL. The URL looks like http://sitename/booking?startdate=28-08-2017

我的代码如下:

aap.module.ts

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 { }

aap.component.ts

aap.component.ts

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令牌,或将基本元素添加到文档中. ; 区域:;任务:Promise.then;值:错误:未设置基本href. 请提供APP_BASE_HREF令牌的值或添加一个底数 元素.

Unhandeled Promise rejection: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document. ; Zone: ; Task: Promise.then ; Value: Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.

Angular如何知道基本href?

How does Angular know the base href?

推荐答案

这应该可以从网址中检索参数:

This should do the trick retrieving the params from the url:

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

本地变量日期现在应包含URL中的 startdate 参数.可以删除Router和Params模块(如果未在该类中的其他地方使用).

The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).

这篇关于如何从角度4的URL中获取参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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