简体   繁体   中英

Property does not exist on type in Service

I do have a service defined to get data from an API:

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

import { bookingClass } from './list/list.component'

@Injectable({
  providedIn: 'root'
})
export class BookingDataService {
  private apiBaseUrl = 'http://localhost:3000/api'

  constructor(private http: HttpClient) { }

  public getAllBookings(): Promise<bookingClass[]> {
    const url: string = `${this.apiBaseUrl}/bookings/listall`
    return this.http
      .get(url)
      .toPromise()
      .then(response => response as bookingClass[])
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('Something has gone wrong', error);
    return Promise.reject(error.message || error);
  }
}

I use this service to populate a list:

import { Component, OnInit } from '@angular/core';
import { BookingDataService } from '../booking-data.service';

export class bookingClass {
  _id: string;
  timestamp: string;
  tags: string[];
  amount: number;
  type: string;
}

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

  constructor(private bookingDataService: BookingDataService) { }

  public bookings: bookingClass[];

  private getBookings(): void {
    this.bookingDataService
      .getAllBookings()
      .then(foundBookings => this.bookings = foundBookings)
  }

  ngOnInit() {
    this.getBookings();
  }

}

When running this with ng serve I'm getting an error

ERROR in src/app/list/list.component.ts(27,8): error TS2339: Property 'getAllBookings' does not exist on type 'BookingDataService'.

which I don't understand, as getAllBookings is public. What am I missing here?

You are having a circular dependency. ListComponent is importing BookingDataService and BookingDataService is in its turn importing bookingClass which is defined inside the list component file.

I can only imagine the error is coming from there. You should move your bookingClass to its own file and export/import it from there.

note: name classes in PascalCase :D and a class is not really necessary here. In my opioning is better to use an Interface , this way your compiled code does not get bloated

该错误与该错误完全无关:我在api调用中使用了错误的端口号,并且在底层express api中输入错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM