错误TypeError:this.dashboardService.getData不是函数

时间:2018-04-10 11:03:23

标签: angular

从组件调用服务时出错。 我试图从提供的URL中获取一些返回JSON的数据。 每次运行此代码时,HTML都会成功加载,但不会调用URL,因为它在getData()上给出了错误,它不是函数 运行时遇到错误。应该采取什么方法来解决它?

this.dashboardService.getData此行中的问题是什么。

Here is the code:

**app.component.ts**

import { Component } from '@angular/core';
import { DashboardService } from './dashboard.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  private apiUrl: "someURL";


  constructor(private dashboardService: DashboardService) { 
    this.getEntries();
  }


  getEntries(){
    this.dashboardService.getData(this.apiUrl).subscribe(data => {
      console.log("data" , data) ;
    })
  }


}



**dashboard.service.ts**

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DashboardService {

  constructor(private http: Http) { }

  getData(apiUrl){
    return this.http.get(apiUrl)
     .map((res: Response) => res.json());
   }
}


**app.module.ts**

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { DashboardService } from './dashboard.service';


@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [DashboardService],
  bootstrap: [AppComponent]
})
export class AppModule { }

2 个答案:

答案 0 :(得分:2)

您缺少AppModule中的HttpModule导入

AVAudioPCMBuffer

答案 1 :(得分:2)

即使错误是 this.dashboardService.getData ,它也会使用HttpClientModule,因为你没有在导入下导入HttpClientModule,它会抛出错误。

修复,添加

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

也可以在导入下添加。

imports: [
       BrowserModule,
       HttpClientModule
]

app.under module.ts

也在您的dashboardService

constructor(private http: HttpClient){
}