javascript - Angular http 发布错误 : Cannot read property 'post' of undefined

标签 javascript angular typescript http dependency-injection

我正在尝试发出我的第一个 HTTP POST 请求。我的 GET 请求工作正常(在同一服务中),但是当我尝试发出 POST 请求时出现错误

ERROR TypeError: Cannot read property 'post' of undefined at ApiService.push../src/app/services/api.service.ts.ApiService.getTracsStartEvents (api.service.ts:57)

我在同一个文件中以与使用 GET 请求相同的方式使用它。我不明白为什么 POST 请求不起作用。我在语法上一定有问题。谁能指出我正确的方向?

import { Device } from '../shared/device';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class ApiService {
  TRACS_URL = '<REMOVED>';
  DELORME_LOCATE_URL = '<REMOVED>';

  apiKey = '<REMOVED>';
  getAllDeviceAPI = 'PApps_AircraftInfo';
  getDeviceByIMEIAPI = 'PApps_AircraftInfo/FindByIMEI/';
  getDeviceByTailNumberAPI = 'PApps_AircraftInfo/FindByTailNumber/';
  getDeviceByCallsignAPI = 'PApps_AircraftInfo/FindByCallsign/';
  getTracsStartEventsAPI = 'GetStartTrackEvents';

  constructor(private httpClient: HttpClient) {}

  public createDevice( device: Device ){}

  public updateDevice( device: Device ) {
    console.log('going to call API to update device: ', device)
  }

  public deleteDevice( device: Device ) {
    console.log('going to call API to delete device: ', device);
  }

  public getDeviceByIMEI( imei: string ) {
    return this.httpClient.get<Device[]>(`${this.TRACS_URL}/${this.getDeviceByIMEIAPI}/${imei}?apikey=${this.apiKey}`);
  }

  public getDeviceByTailNumber( tailNumber: string ) {
    return this.httpClient.get<Device[]>(`${this.TRACS_URL}/${this.getDeviceByTailNumberAPI}/${tailNumber}?apikey=${this.apiKey}`);
  }
  public getDeviceByCallsign( callsign: string ) {
    return this.httpClient.get<Device[]>(`${this.TRACS_URL}/${this.getDeviceByCallsignAPI}/${callsign}?    apikey=${this.apiKey}`);
  }
  public getAllDevices( url?: string ) {
    return this.httpClient.get<Device[]>(`${this.TRACS_URL}/${this.getAllDeviceAPI}?apikey=${this.apiKey}`);
  }

  public getTracsStartEvents( imeiList: string[] ) {
    console.log('imeiList: ', imeiList );
    const httpHeaders = new HttpHeaders({
        'x-api-key': 'Ra4GyPWuzU1PKDKdmHyyK4WlMKV7v3j4JQhaU7i8',
        'Content-Type': 'application/json-patch+json',
        'Cache-Control': 'no-cache',
    });
    let options = {
      headers: httpHeaders
    };
    return this.httpClient.post<any[]>    (`${this.DELORME_LOCATE_URL}/${this.getTracsStartEvents}`,
      {
        data: { arr_imei: imeiList,
                searchType: 'REALTIME',
              }
      }, options ).subscribe( res => {
        console.log('query result:', res );
      });
    }
}

这里是我调用 post 函数的地方(这是来自另一个用于获取位置更新的服务):

import { Injectable } from '@angular/core';
import { ApiService } from './api.service';

import { GeoJson } from '../shared/geo-json';

@Injectable({
  providedIn: 'root'
})

export class PositionUpdateService {
  positionUpdate: GeoJson;

  constructor(private apiService: ApiService,
              ) {
    this.positionUpdate = new GeoJson( 'Feature',
    {type: 'Point', coordinates: [-121.0, 37.5, 1000]} );
    //console.log('posUpdate: this.positionUpdate: ', this.positionUpdate );
 }

  getMissionStartEvents( devices ) {
    console.log('posUpdate svc, getMissionStartevents, imeis: ', devices);
    const events =  this.apiService.getTracsStartEvents( devices );
    console.log(events);
  }
}

这一切都从我的 HomeComponent 开始:

export class HomeComponent implements OnInit, OnChanges {
   constructor(public appSettingsService: AppSettingsService,
               public layerControlDialogComponent: MatDialog,
               private devicesToTrackService: DevicesToTrackService,
               private positionUpdateService: PositionUpdateService,
               private httpClient: HttpClient) { }
  startTracking(devices) {
     console.log('going to start tracking ', devices);
     this.positionUpdateService.getMissionStartEvents(devices)
  }

最佳答案

确保将您的 ApiService 注释为 Injectable():

@Injectable({
  providedIn: 'root',
})
export class ApiService {

然后,不要自己创建 ApiService,这就是依赖注入(inject)的目的。它将自动创建一个 ApiService 实例及其依赖项(在本例中为 HttpClient):

export class PositionUpdateService {
  // The dependency injection will automatically instantiate ApiService
  constructor(private apiService: ApiService) {
   }

  // ...
}

关于javascript - Angular http 发布错误 : Cannot read property 'post' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55479473/

相关文章:

javascript - 选择 p 文本 jquery

angular - Angular 5+ 中的服务继承

javascript - JS Date() 对象的奇怪之处

javascript - 如何创建一个包含元组的集合,其中每个元组必须是唯一的?

Javascript 继承并丢失 'this' 的上下文

javascript - 返回嵌套的可观察值

angular - 找不到 NgModule。使用 skip-import 选项跳过 NgModule 中的导入

angular - navigator.geolocation.watchPosition 返回位置不可用

javascript - Typescript - 调用从另一个文件导出的类。

javascript - 如何避免使用 typescript 生成的表单中的换行?