Angular http发布错误:无法读取未定义的属性“ post”

时间:2019-04-02 16:25:11

标签: javascript angular typescript http dependency-injection

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

  

错误TypeError:无法读取未定义的属性“ post”           在       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)
  }

2 个答案:

答案 0 :(得分:0)

请确保将ApiService注释为Injectable()

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

然后,不要自己创建ApiService,这就是依赖项注入的作用。它将自动创建具有相关性的ApiService实例(在这种情况下为HttpClient):

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

  // ...
}

答案 1 :(得分:0)

首先,http.get和http.post返回observables,除非您订阅它,否则希望不会执行,就像这样:

this.apiService.getTracsStartEvents(devices).subscribe()

第二,Angular中的依赖项注入无法像这样工作。

  1. 不要使用new关键字实例化apiService,就像直接使用this.apiService来使用httpClient一样,直接使用它。

  2. 最后确保您提供了apiService,否则请输入以下内容:

    @Injectable({providedIn: ‘root’})
    export class ApiService { ...
    

而且get方法也不应该起作用。如果尝试订阅它,则可能会有相同的错误,可能是由于构造函数中的apiService实例化。