Angular2 Query Parameter from index URL

眉间皱痕 提交于 2019-12-02 01:45:40

问题


I am trying to get the query params from a url in a component in Angular2

Version: "angular2": "npm:angular2@2.0.0-beta.12",

I am trying to extract id query param in the component and display it

Here is the request.

localhost:8080/index.html?id=1

boot.ts

import 'reflect-metadata';
import 'angular2/bundles/angular2-polyfills';
import { bootstrap } from 'angular2/platform/browser';
import { provide} from 'angular2/core';
import { AppComponent } from './app.component';
import {ROUTER_PROVIDERS, Location, LocationStrategy,     HashLocationStrategy} from "angular2/router";
import {HTTP_PROVIDERS} from "angular2/http";

bootstrap(AppComponent , [ROUTER_PROVIDERS, HTTP_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]);

Here is app.component.ts

import { Component } from 'angular2/core';
 import {Router, Location, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from 'angular2/router';

@Component({
    selector: 'my-app',
    template: '{{welcome}} {{queryParam}}',
    directives: [ROUTER_DIRECTIVES]
})
export class AppComponent {
    welcome: string = 'Query Param test!'
    queryParam : string;

    constructor(private _location: Location, private _routeParams:     RouteParams){
        console.log(_routeParams.get('id'));
        this.queryParam = _routeParams.get('id');
    }

}

I keep getting this error:

error message

I got this solution from another post. Not sure how to fix the error

A


回答1:


RouteParams it's not available in the root component. It's only available to the routable components.

See RouterOutlet soure code, in its activate function, you can see the following

var providers = Injector.resolve([
  provide(RouteData, {useValue: nextInstruction.routeData}),
  provide(RouteParams, {useValue: new RouteParams(nextInstruction.params)}),
  provide(routerMod.Router, {useValue: childRouter})
]);

Basically RouteParams is being injected through RouterOutlet to the routable components, you can't access it in non-routable components (sorry for repeating myself).




回答2:


You can get the query params from the _location.path() in the AppComponent. You'd have to parse them yourself. I'm looking for the same thing, and haven't found a better solution.

I hope someone else follows up on this.



来源:https://stackoverflow.com/questions/36318761/angular2-query-parameter-from-index-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!