无法从其余Angular 6获取数据

时间:2018-06-21 06:04:26

标签: javascript angular rest angular6

我正尝试从rest api获取数据,

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

@Component({
  selector: 'app-broker-ui',
  templateUrl: './broker-ui.component.html',
  styleUrls: ['./broker-ui.component.css']
})
export class BrokerUIComponent implements OnInit {

  constructor(private _http:HttpClient) {

   }

  ngOnInit() {
    this.load_broker_list();
  }

  load_broker_list(){
   return this._http.get("http://localhost:8080/broker/all")
                     .subscribe(
                      (data:any[]) => {
                       console.log(data);
                      }
                     )

  }

}

但这不是console.log数据,这里是示例数据

[ 
  { id: 1, username: "AAA" }, 
  { id: 2, username: "BBB" }, 
  { id: 3, username: "CCC" }, 
  { id: 4, username: "DDD" }, 
  { id: 5, username: "EEE" } 
]

这是我遇到的错误,

  

错误:StaticInjectorError(AppModule)[BrokerUIComponent->   HttpClient]:StaticInjectorError(平台:核心)[BrokerUIComponent->   HttpClient]:NullInjectorError:HttpClient没有提供程序!

2 个答案:

答案 0 :(得分:0)

在DI中找不到

HttpClient类。您需要将HttpClientModule添加到AppModule的导入中。

示例

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

@NgModule({
   imports: [
      ...
      HttpClientModule
      ...
   ]
})
export class AppModule { }

答案 1 :(得分:0)

在向应用程序中使用任何HTTP服务之前,您需要将HttpClientModule导入到app-module.ts(主模块)中,就像这样-

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

@NgModule({
   imports: [
     HttpClientModule
     // OtersModules
      ...
   ]
})
export class AppModule { 
 }