angular - 服务中的类型不存在属性
问题描述
我确实定义了一项服务来从 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
是公开的。我在这里想念什么?
解决方案
你有一个循环依赖。ListComponent
正在导入BookingDataService
,然后BookingDataService
又在导入bookingClass
列表组件文件中定义的导入。
我只能想象错误来自那里。您应该将您的文件移动bookingClass
到它自己的文件并从那里导出/导入它。
注意:在 PascalCase :D 中命名类,并且这里不需要一个类。在我看来,最好使用Interface
,这样您的编译代码不会变得臃肿
推荐阅读
- string - 我被这段代码卡住了,为什么它不起作用?
- swift - 无法转换“ClosedRange”类型的值
' 到预期的参数类型 'Range<_>' - android - ImageView 显示不正确
- python - 如何结束模块定义?
- c# - 无法从字典中获取值
- python - 如何执行python文件?
- python - Django 错误:“您正在尝试在没有默认值的情况下将不可为空的字段‘作者’添加到条目中”
- c# - 如何在 AspNet Core gRPC Service 中导入 protobuf 知名类型
- php - 我的问题是关于用 php 创建一个乘法表
- r - R:path.expand(路径)中的错误:无效的“路径”参数