routing - Angular 2 错误 : Cannot resolve all parameters for 'RouteParams'

标签 routing angular

尝试使用 RouteParams 获取查询字符串参数,但我只是得到错误

Cannot resolve all parameters for 'RouteParams'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteParams' is decorated with Injectable. angular2-polyfills.js:332 Error: Cannot read property 'getOptional' of undefined.......

看看这个 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 已更新)...

最佳答案

中移除RouteParams
bootstrap(AppComponent, [ROUTER_PROVIDERS, RouteParams]);

RouteParams 由路由器提供。如果您自己提供,则注入(inject)失败。

参见 https://angular.io/api/router/Params举个例子。 RouteParams 只能注入(inject)到路由器添加的组件上。

Plunker example

关于routing - Angular 2 错误 : Cannot resolve all parameters for 'RouteParams' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496752/

相关文章:

javascript - 当我从使用服务获取的数组中删除一个元素时,它在哪里被删除?

json - 当 format=json 时响应_with 重定向

javascript - 从 NodeJS 内部调用 Express Route

laravel - Laravel错误Symfony\Component\HttpKernel\Exception\HttpException

ruby-on-rails - RoR 中的 SEO 友好 URL

angular - 有条件地将类应用于组件主机

javascript - ionic 2 中 Promise 函数内的 nav

angular - 发生未处理的异常 : The 'buildOptimizer' option cannot be used without 'aot'

angular - 动态创建 formGroup 时,control.setParent 不是函数

api - Google Directions API 的替代品