【问题标题】:Invalid providers无效的提供者
【发布时间】:2016-12-14 04:25:07
【问题描述】:

我与提供者有一些困难。我尝试在组件中导入新的自定义提供程序,但它不起作用。 第二个提供程序基于我制作的第一个提供程序,并且运行良好...

这是我的提供者:

import { Injectable} from "@angular/core";
import { Router, Routes } from '@angular/router';

import ... // All components needed

@Injectable()
export class RoutesHelper {

  private userRoutes: Routes = [
      { path: '' , component: HeaderComponent, outlet: 'header' },
      ...
    ];


  constructor(
    private router:Router
    ) {}

    public load() {
      this.router.resetConfig(this.userRoutes);
    }
}

这是我的“问题组件”

import { Component, OnInit } from '@angular/core';
import { RoutesHelper } from '../_utils/routes.helper';

@Component({
  selector: 'questions-list',
  templateUrl: './app/question/questions.component.html',
  providers: [RoutesHelper]
})

export class QuestionsComponent implements OnInit {

  constructor(private routes:RoutesHelper) {}

  ngOnInit() {
    this.routes.load();
  }
}

但我有这个错误: “QuestionsComponent”的提供者无效 - 只允许提供 Provider 和 Type 的实例,得到:[?undefined?]

我不知道为什么我得到“未定义”对象,我也没有这个错误。

感谢您的帮助。

【问题讨论】:

  • 你是否在 app.module.ts 文件中包含了你的提供者?
  • 是的,提供程序包含在 app;module.ts 中
  • 正在导入链接并包含在提供者列表中?

标签: angular angular-providers


【解决方案1】:

在 app.module.ts 文件中导入提供者的链接。

从“给出你的路径”导入 { RoutesHelper };

在 app.module.ts 提供者列表中包含提供者类名。

providers: [RoutesHelper, //你的其他供应商...],

在您的 QuestionComponent 中,只需导入 RoutesHelper 链接即可。无需定义提供者。

【讨论】:

  • 我试过了,我得到一个新的错误:Can't resolve all parameters for QuestionsComponent: (?)。有什么想法吗?
【解决方案2】:

好的,问题解决了。

避免由于在提供程序中导入组件而在组件中导入的最后一个错误(因此递归导入)。 我用过这个:

var userRoutes: Routes = [
    { path: '' , component: LeftComponent, outlet: 'left' },
    { path: '' , component: EmptyComponent, outlet: 'footer' },
    { path: '' , component: HeaderComponent, outlet: 'header' }
];

var all = userRoutes.concat(this.router.config);
this.router.resetConfig(all);

其中 userRoutes 只包含我想要覆盖的出口并且它可以工作。

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多