2016-08-05 83 views
-1

我想通过url查询参数将参数传递给我的Angular2应用程序。 因此,如果用户在浏览器的地址栏中输入http://myapp.com?r=www.stackoverflow.com,我希望获取参数r的值以将其存储在sessionStorage中并稍后使用它。我不想将这个值从组件传递给组件。将参数传递给Angular 2(RC4)应用程序

这样做的正确方法是什么?我是否需要在我的路线中配置它,如果是这样,我该怎么做?

export const routes: RouterConfig = [ 
     { path: ':r', component: LandingComponent }, 
    .... 

那没有工作或我无法弄清楚如何获得价值。

感谢您的帮助!

+0

你想从浏览器URL栏或默认路由中传递它们吗?是关于如何在代码中添加它们,或者如何在代码中读取它们的问题? –

+0

是我的答案,你在找什么? –

+0

@GünterZöchbauer我想从浏览器URL传入参数,所以问题是关于在代码中读取它。例如。当用'http://myapp.com?r=www.stackoverflow.com'调用我的应用程序时,我想在启动时读取参数'r'的值,然后在某个时候使用它。 – tschuege

回答

0

我finaly通过得到的文件注入到构造

constructor(@Inject(DOCUMENT) private document: any) 

,解决它,然后从

this.document.location.search 

这对我的作品得到的参数,如香草JavaScript,但我不知道,如果它适用于Angular2可以运行的所有环境。

1

你可以传递参数的URL这样

<a [routerLink]="['/about', { foo: 'foo' }]">About</a> 

import { Component , OnInit } from "@angular/core"; 
import { Title } from "@angular/platform-browser"; 
import { ActivatedRoute } from "@angular/router"; 
import { Observable }  from "rxjs/Observable"; 

@Component({ 
    template: "<h1>About page! {{ paramName | async }}</h1>", 
}) 

export class AboutComponent implements OnInit { 
     public constructor(private route: ActivatedRoute) {} 
    public paramName: Observable<string>; 
    public ngOnInit() { 
     // console.log("App component loaded"); 
     this.setTitle("about"); 
     this.paramName = this.route.params.map(params => params["foo"] || "None"); 
    } 
}; 
+0

这适用于将参数从一个组件传递到另一个组件。我正在努力的是在启动时传入参数。所以,当用'http://myapp.com?r = www.stackoverflow.com'启动我的应用程序时,我想在启动时捕获param'r'的值,然后忘掉它。 – tschuege

+1

这应该是你正在寻找,但'queryParams'而不是'params'。这不是*用于在组件之间传递参数。 –

+0

@GünterZöchbauer根据[docs](https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html),RC4上的ActivatedRoute中没有queryParams。 Params的类型为Observable - 但是当我订阅它时,就像'this.activatedRoute.params .map(params => params ['r']) .subscribe((r)=> {alert} r:“+ r); });'我没有得到通过URL传入的值。 'this.activatedRoute.snapshot.params.r'也不包含该值。 – tschuege

0

已配置的路线是正确的,下面是解决如何获得查询参数。

这里是Plunker!!

export const routes: RouterConfig = [ 
    { path: '', redirectTo: '123', terminal: true }, 
    { path: ':id', component: LandingComponent } 
]; 

    @Component({ 
    selector: 'landing-component', 
    template: ` 
    landing component 
    ` 
    }) 
    export class LandingComponent { 
    id = ""; 
    constructor(private route: ActivatedRoute) {} 

    ngOnInit() { 
    const s: ActivatedRouteSnapshot = this.route.snapshot; 
    this.id = s.params["id"]; 
    console.log(this.id); 
    } 
    } 

希望这有助于!

+0

不知道我是否理解你的权利。这将“主要组件”的值123传递给着陆组件。但我想通过浏览器的URL传递值123。 – tschuege

相关问题