【发布时间】:2018-08-13 12:16:21
【问题描述】:
我有一个 Angular 应用程序,我使用 HttpClient 从 API 检索数据。
我想从 API 获取原始数据并将它们发送到相应的服务。这些服务具有将原始数据映射到模型对象并将它们返回给组件的方法。
问题是,我从 API 获取数据(返回 Observable),我订阅了服务方法,然后我不知道如何将数据传递给组件。
我从 API 检索数据的 API 服务。然后我发送原始数据和酒店服务,我想将原始数据映射到模型并发送到组件
@Injectable()
export class ApiService {
...
public getHotelById(hotelId: number): Observable<any> {
return this.http
.get(API_URL + '/hotel/' + hotelId)
.map((response) => {
return response;
})
}
...
}
@Injectable()
export class HotelService {
...
public getHotelById(id: number): Subscription {
return this.api.getHotelById(id).subscribe(
(response) => {
let hotel = new HotelModel(response.hotel);
hotel.mapCountry(response.country);
return hotel;
}
);
}
...
}
谁能帮助我如何从组件中的服务中检索数据?我收到酒店服务返回的对象是订阅的错误,我无法订阅它。
有什么方法可以做到这一点吗?我不想在 API 服务中做一些业务逻辑。在那个地方我只想检索数据。
组件方法
ngOnInit() {
this.activatedRoute.queryParamMap.subscribe(
(map) => {
this.hotelId = this.activatedRoute.snapshot.params['id'];
this.hotel = this.hotelService.getHotelById(this.hotelId)
.subscribe(
(hotel) => {
this.hotel = hotel;
}
)
}
)
}
【问题讨论】:
标签: angular typescript rxjs angular-cli