繁体   English   中英

组件中的Angular 4 HttpClient无法解析所有参数

[英]Angular 4 HttpClient in Component Can't resolve all parameters

我开始学习 Angular 4 并开始学习 HTTP 客户端。 现在我正在尝试从组件进行 http 调用(是的,我知道我应该将它转移到服务,但仍然)

但是出于某种原因,当我尝试将 HttpClient 注入到我的组件中时,我收到了下一个错误:

未捕获的错误:无法解析 PromocodeComponent 的所有参数:(?)。

这是我的组件的代码:

import { Ticket } from '../../classes/Ticket.class'
import { Component, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'promocode',
  templateUrl: './promocode.template.html',
  styleUrls: ['./promocode.styles.scss']
})
export class PromocodeComponent {
  @Input() ticket: Ticket;
  state: String = "normal";
  promocode: String = "";

   constructor(private http: HttpClient) {}

  promocodeValidate(event): void{
    console.log(this.promocode);
    console.log(event);
    this.http.get('/promocode/asdasda').subscribe(data => {
      console.log(data);
    });
  }
}

还有我的 app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MovieBadgeComponent } from './movie-badge/movie-badge.component';
import { TicketComponent } from './ticket/ticket.component';
import { PromocodeComponent} from './promocode/promocode.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    MovieBadgeComponent,
    TicketComponent,
    PromocodeComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

事实证明,对我而言,我忘记了服务上的@Injectable装饰器。 在早期的角度(> = 2)中,我记得@Injectable是可选的......猜不再了?

事实证明,我错过了

“emitDecoratorMetadata”:true

在tsconfig中

FML ...

您可能需要升级开发环境:

  • 节点
  • 角度cli
  • 角度的版本

然后再试一次

当我使用Angular运行单元测试(spec.ts文件)时,我得到了同样的错误。

以下是我的所作所为:

     import { HttpClientModule, HttpClient } from '@angular/common/http'; 

     beforeEach(async(() => {
       TestBed.configureTestingModule({
         declarations: [ ],
         imports: [
           HttpClientModule
         ],
         schemas: [NO_ERRORS_SCHEMA],
         providers: [
           HttpClient,
         ]
       })
         .compileComponents();
      }));

而错误消失了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM