我确实定义了一个服务来从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
是公开的。我在这里想念什么?
答案 0 :(得分:1)
您具有循环依赖关系。 ListComponent
正在导入BookingDataService
,而BookingDataService
又正在导入bookingClass
,这是在列表组件文件中定义的。
我只能想象错误是从那里来的。您应该将bookingClass
移至其自己的文件,然后从那里导出/导入它。
注意:在PascalCase:D中命名类,这里实际上并不需要一个类。在我看来,最好使用Interface
,这样您的编译代码不会肿
答案 1 :(得分:0)
该错误与该错误完全无关:我在api调用中使用了错误的端口号,并且在底层express api中输入错误。