【问题标题】:Angular 2 DI can't resolve parameters, HTTP client moduleAngular 2 DI 无法解析参数,HTTP 客户端模块
【发布时间】:2018-04-16 08:35:12
【问题描述】:

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

【问题讨论】:

  • 那里没有明显的问题,你能用 Plunker 给minimal reproducible example 吗?
  • 是的,如果没有明显的亮点,我会考虑创建一个 Plunker。让我难倒了好久。
  • @Andrew 我也遇到了同样的问题,这个有什么好运气吗?

标签: javascript angular angular-components angular-httpclient


【解决方案1】:

尝试使用Http 导入而不是HttpClient

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

【讨论】:

  • HttpClient 类是有效的参考这个documentation*
  • 这取决于 Angular 的版本。
  • 我一开始使用的是 Http,但我遇到了其他错误,然后我找到了上面的文档,我使用的是 4.3.4,所以看起来 HttpClient 是可以使用的。
【解决方案2】:

根据这个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'];
        });
    }
}

【讨论】:

猜你喜欢
  • 2017-10-05
  • 2020-12-10
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 2019-08-01
  • 2016-12-13
  • 2023-02-02
  • 2017-07-06
相关资源
最近更新 更多