首页 > 解决方案 > 服务中的类型不存在属性

问题描述

我确实定义了一项服务来从 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);
  }
}

我使用此服务来填充列表:

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();
  }

}

使用 ng serve 运行此程序时出现错误

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

我不明白,因为getAllBookings是公开的。我在这里想念什么?

标签: angular

解决方案


你有一个循环依赖。ListComponent正在导入BookingDataService,然后BookingDataService又在导入bookingClass列表组件文件中定义的导入。

我只能想象错误来自那里。您应该将您的文件移动bookingClass到它自己的文件并从那里导出/导入它。

注意:在 PascalCase :D 中命名类,并且这里不需要一个类。在我看来,最好使用Interface,这样您的编译代码不会变得臃肿


推荐阅读