【问题标题】:Angular 2 : Can't resolve all parameters for ActivatedRouteAngular 2:无法解析 ActivatedRoute 的所有参数
【发布时间】:2017-12-20 11:32:35
【问题描述】:

我已经为 activedroute 添加了提供程序,现在它给出了这个错误,我想获取查询字符串参数,例如:http://localhost:4200/?user=hello

我想获得用户的价值,这是我的代码:

import { Component, OnInit, Input } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';



@Component({
selector: 'app-login',
templateUrl: './login.html'
})

export class LoginBancaComponent implements OnInit  {

constructor(private route: ActivatedRoute){}



ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
    let str= params['user'];
    console.log(str);
  });
 }


}

但在控制台页面上出现此错误:

无法解析 ActivatedRoute 的所有参数:(?, ?, ?, ?, ?, ?, ?, ?)。

我已经导入了模块中的所有内容:

import {Router, ActivatedRoute, Params} from '@angular/router';
...
imports: [
BrowserModule,
CommonModule, RouterModule,
],
providers: [ActivatedRoute],
...

为什么会出现这个错误?

【问题讨论】:

  • 你能在这里打印出什么确切的错误
  • 未捕获的错误:无法解析 ActivatedRoute 的所有参数:(?, ?, ?, ?, ?, ?, ?, ?)。在 CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getDependenciesMetadata (vendor.bundle.js:35399) 处的 syntaxError (vendor.bundle.js:21312) 处跨度>
  • Robby Cornelissen 我刚刚阅读了这个问题,但我不知道您如何使用 RouterModule.forRoot()

标签: angular


【解决方案1】:

您不需要自己提供ActivatedRouteRouterModule 中已经提供了。您收到此错误,因为ActivatedRoute 可能具有您未提供的其他依赖项。只需将其从模块中的 providers 数组中删除即可。

【讨论】:

  • 完成,但现在它可以工作了,但它在未定义的控制台上打印
  • 这是您的根模块还是功能模块?
  • 那么它解决了你的错误吗? undefined 可能是因为您的 let str= params['user']; 行。您可能没有传递user 参数。
【解决方案2】:
// 1. inject activatedRoute with name 'route'
constructor(private route: ActivatedRoute){ }

ngOnInit() {
    // 2. use right name 'route' as injected above
    this.route.params.subscribe((params: Params) => {
        let str = params['user'];
        console.log(str);
    });
}

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 2017-03-23
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2016-11-08
    • 2017-11-06
    相关资源
    最近更新 更多