【发布时间】:2016-07-29 13:10:43
【问题描述】:
尝试使用 RouteParams 获取查询字符串参数,但我得到了错误
无法解析 'RouteParams'(?) 的所有参数。确保所有 参数用 Inject 修饰或具有有效类型 注释并且“RouteParams”用 Injectable 装饰。 angular2-polyfills.js:332 错误:无法读取属性“getOptional” 未定义.......
看看这个Plnkr。如何在不收到此警告的情况下使用 RouteParams?
重要的文件是:
boot.ts:
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, RouteParams} from 'angular2/router';
import {AppComponent} from './app/app.component';
bootstrap(AppComponent, [ROUTER_PROVIDERS, RouteParams]);
和app.component.ts:
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from "angular2/router";
@Component({
selector: 'app',
template: `
<p *ngIf="guid">guid gived is: {{guid}}</p>
<p *ngIf="!guid">No guid given in query-string in URL</p>
`
})
export class AppComponent implements OnInit {
guid:string;
constructor(private _params: RouteParams) {} //
ngOnInit() {
this.guid = this._params.get('guid');
}
}
更新:
我没有任何路由,我只有默认的根路由(如果在我没有其他路由时可以将其称为路由...)。但是按照 Gianluca 的建议,我添加了以下路由配置:
@RouteConfig([
{ path: '/:guid', name: 'Home', component: AppComponent, useAsDefault: true },
])
但我仍然遇到同样的错误(Plnkr 已更新)...
【问题讨论】:
-
这个
guid来自哪里?如果你没有任何路线? -
这只是我的应用程序需要的查询字符串,所以有人会这样使用它:mydomain.com/myapp?guid=something。也许在这里可以称它为其他名称,例如“testparamenter”之类的......
-
我刚刚发布了我的答案,希望对您有所帮助。