我正在制作一个角度为5的网站。我正在其中一个组件中使用输入绑定。
<app-recommend-popular [comp]="component" [recommended]="recommendedHotels" [popular]="popularHotels"></app-recommend-popular>
对于'recommendedHotels',我从HTTP Service获取数据。从mongo DB我只获取三条记录。它是一个JSON对象。它看起来应该像 figure1
@Component({
selector: 'app-recommend-popular',
templateUrl: './recommend-popular.component.html',
styleUrls: ['./recommend-popular.component.css']
})
export class RecommendPopularComponent implements OnInit{
@Input() comp: string;
@Input() recommended: string;
@Input() popular: string;
public recommendedThings: string[];
constructor() {
}
getRepeater(ratingTotal) {
return new Array(ratingTotal);
}
ngOnInit() {
}
}
HTML CODE就在这里:
<div class="card-deck">
<div class="card" *ngFor="let r of recommended">
<img class="card-img-top" src="{{ r.Image }}" alt="Card image cap">
<div class="cardbody">
<div class="row">
<div class="col-sm-6 col-xs-6">
<h5 class="card-title">{{ r.Name }}</h5>
</div>
<div class="col-sm-6 col-xs-6 alignRight">
<p style="float: right">PKR {{ r.Price }}</p>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-xs-6">
<div>
<span *ngFor="let str of getRepeater(r.Rating)" class="fa fa-star" aria-hidden="true"></span>
</div>
<div>
{{ r.Rating }}/5 (120 reviews)
</div>
</div>
<div class="col-sm-6 col-xs-6 alignRight">
<a class="btn btn-success" routerLink="/review">View Deal</a>
</div>
</div>
</div>
</div>
</div>
以下是服务代码:
GetRecommendedHotels(latitude, longitude) {
return this.http.get('http://localhost:3000/app/hotels/Lahore/5')
.map((response: Response) => {
const gethotels = response.json().obj;
console.log(gethotels);
for (const hotel of gethotels) {
this.transformedhotels.push(new Hotel(hotel.Name, hotel.Location, hotel.Price, hotel.Rating, hotel.TotalRooms, hotel.FreeRooms, hotel.Image));
}
this.hotels = this.transformedhotels;
return this.transformedhotels;
})
.catch((error: Response) => Observable.throw(error));
}
获取代码(在'酒店'组件构造函数中)
constructor(private hotelService: HotelService) {
this.hotelService.GetRecommendedHotels(this.latitude, this.longitude).subscribe((hotels: Hotel[]) => {
this.recommendedHotels = hotels;
console.log('calling1');
});
}
有人能建议我更好的方式吗?
答案 0 :(得分:0)
您正在推送现有阵列中的最新数据,每当您从后端获得更新数据时都会清除现有阵列。
GetRecommendedHotels(latitude, longitude) {
return this.http.get('http://localhost:3000/app/hotels/Lahore/5')
.map((response: Response) => {
const gethotels = response.json().obj;
this.transformedhotels = []; <==============================
console.log(gethotels);
for (const hotel of gethotels) {
this.transformedhotels.push(new Hotel(hotel.Name, hotel.Location, hotel.Price, hotel.Rating, hotel.TotalRooms, hotel.FreeRooms, hotel.Image));
}
this.hotels = this.transformedhotels;
return this.transformedhotels;
})
.catch((error: Response) => Observable.throw(error));
}