[英]Subscription to Observable
我有一個Angular應用,使用HttpClient從API檢索數據。
我想從API獲取原始數據並將其發送到相應的服務。 這些服務具有將原始數據映射到模型對象並將其返回給組件的方法。
問題是,我從API獲取數據(返回Observable),我訂閱了service方法,然后我不知道如何將數據傳遞給組件。
我從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;
}
);
}
...
}
誰能幫助我如何從組件中的服務檢索數據? 我收到錯誤消息,hotelservice返回的對象是訂閱,我無法訂閱。
有什么辦法嗎? 我不想在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;
}
)
}
)
}
map
您的響應,而不是訂閱它。 訂閱是“道路的盡頭”,而地圖只是“變道”。
export class HotelService {
...
public getHotelById(id: number) {
return this.api.getHotelById(id).pipe(map(
(response) => {
let hotel = new HotelModel(response.hotel);
hotel.mapCountry(response.country);
return hotel;
}
));
}
...
}
我認為對您來說,一種好的方法是將結果映射到特定的函數“ getHotelById”中(您可以像創建ORM)
@Injectable()
export class ApiService {
...
public getHotelById(hotelId: number): Observable<any> {
return this.http
.get(API_URL + '/hotel/' + hotelId)
.map((response) => {
let hotel = new HotelModel(response.hotel);
hotel.mapCountry(response.country);
return hotel;
})
}
...
}
@Injectable()
export class HotelService {
...
public getHotelById(id: number): Observable<any> {
return this.api.getHotelById(id);
}
...
}
在您的組件中,沒有任何變化。
您真的需要兩項服務嗎?
@Injectable()
export class HotelService extends AbstractHttpService {
constructor (
private httpClient: HttpClient,
) {
super();
}
loadHotels(): Observable<Hotel[]> {
const url = this.url('hotels');
return this.httpClient.get<Hotel[]>(url, this.standardHttpOptions);
}
}
抽象類具有一些用於查詢目標URL的幫助程序,並為get調用提供了標准的http選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.