Angular 2 DI 无法解析参数,HTTP 客户端模块



我正在学习使用 Angular 2,并且已经到了这里的一个点,我遇到了下面的错误。这仅在添加 httpClientModule 并尝试从组件 ngInit 发出 http get 请求后出现。该应用程序使用的是角度 4.3.4。

Can't resolve all parameters for BlogComponent: (?).

app.module.ts 的内容

    import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { BlogComponent } from './blog.component';
import { HomeComponent } from './home.component';

import { appRoutes } from './routes'
@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes)
  ],
  declarations: [
    AppComponent,
    BlogComponent,
    HomeComponent
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

引发错误的博客组件 TS 文件的内容

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'test-blog',
  template: '<h1>Blog page :)</h1>',
})
export class BlogComponent implements OnInit{
  results: string[];
  constructor(private http: HttpClient) {}
  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/blog/all').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

尝试导入Http而不是HttpClient

import { Http } from '@angular/http';
...
constructor(private http: Http) {}

根据本教程,您的组件可能缺少@Injectable() .

请尝试以下操作:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'test-blog',
  template: '<h1>Blog page :)</h1>',
})
@Injectable()
export class BlogComponent implements OnInit{
results: string[];
constructor(private http: HttpClient) {}
    ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/blog/all').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
        });
    }
}

最新更新