索引URL的Angular2查询参数 [英] Angular2 Query Parameter from index URL
问题描述
我正在尝试从Angular2组件中的URL获取查询参数
I am trying to get the query params from a url in a component in Angular2
版本:"angular2":"npm:angular2@2.0.0-beta.12",
Version: "angular2": "npm:angular2@2.0.0-beta.12",
我正在尝试提取组件中的id查询参数并显示它
I am trying to extract id query param in the component and display it
这是请求.
localhost:8080/index.html?id = 1
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})]);
这是app.component.ts
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 got this solution from another post. Not sure how to fix the error
A
推荐答案
RouteParams
it's not available in the root component. It's only available to the routable components.
请参见 RouterOutlet
源代码,其激活函数,您可以看到以下
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})
]);
基本上,RouteParams是通过RouterOutlet注入到可路由组件中的,您不能在不可路由组件中访问它(对不起,请重复我自己).
Basically RouteParams is being injected through RouterOutlet to the routable components, you can't access it in non-routable components (sorry for repeating myself).
这篇关于索引URL的Angular2查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!