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

时间:2017-11-03 14:56:55

标签: javascript angular angular-components angular-httpclient

我正在学习使用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'];
    });
  }
}

2 个答案:

答案 0 :(得分:0)

尝试使用Http导入而不是HttpClient

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

答案 1 :(得分:0)

根据此tutorial,您的组件可能会丢失@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'];
        });
    }
}