1

我正在学习使用 Angular 2 并且已经达到了一个点,我遇到了下面的错误。这仅在添加 httpClientModule 并尝试从组件 ngInit 发出 http get 请求后才出现。该应用程序使用 Angular 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'];
    });
  }
}
4

2 回答 2

0

根据本教程,您的组件可能会丢失@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'];
        });
    }
}
于 2017-11-26T16:16:23.270 回答
0

尝试使用Httpimport 而不是HttpClient

import { Http } from '@angular/http';
...
constructor(private http: Http) {}
于 2017-11-03T15:05:41.090 回答