参数与构造函数中的私有参数不匹配

Parameter mismatch with private parameters in constructor

本文关键字:参数 不匹配 构造函数      更新时间:2023-09-26

TL:DR:在尝试使用私有构造函数参数时获得错误Supplied parameters do not match any signatures of call targetconstructor (private http: Http) {}

我在Angular2中设置私有参数时遇到了一些麻烦。我曾经认为,当一个属性在构造函数中声明为私有时,它不需要传入。这对我来说似乎很奇怪,我猜我对这一点的理解是错误的,但我找不到任何信息表明不是这样。下面是我的意思的一个例子:

constructor (private http: Http) {} from https://angular.io/docs/ts/latest/guide/server-communication.html

然后引用http属性,但是我没有看到任何http实例被传递到其他地方。

我试图实现同样的事情,但我得到以下错误:Supplied parameters do not match any signatures of call target,这似乎意味着需要将Http实例传递给构造函数。

该程序是为"卡片"的"画廊"。卡片从使用Http的CardService传递。这段代码目前在mainGallery: Gallery = new Gallery();

行抛出错误

import { Component } from '@angular/core';
import { Gallery } from './gallery';
import { CardService } from './card.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ CardService ]
})
export class AppComponent {
    title = 'app works!';
    
    mainGallery: Gallery = new Gallery();
}

这是画廊的样子:

@Component({
    providers: [CardService]
})
export class Gallery{
    cards: Card[] = [];
    constructor(private cardService: CardService){
    }
}

如果我试图在card服务的构造函数中使用private http: Http,我也会得到相同类型的错误。任何帮助都非常感激!


编辑:这是我的NgModule:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

我认为你不能简单地创建一个new Gallery(),你必须要求相关的注入器为你获取一个,因为你没有向Gallery的构造函数发送任何参数,这是注入器的工作。

阅读这里:https://angular.io/docs/ts/latest/guide/dependency-injection.html