我正在用angular 5制作一个网站,我在其中一个组件中使用了输入绑定。
<app-recommend-popular [comp]="component" [recommended]="recommendedHotels" [popular]="popularHotels"></app-recommend-popular>对于'recommendedHotels‘,我从HTTP DB获取数据,我只获取三个records.It是Service.From对象。它应该看起来像figure1中的那样
‘’app recommend popular‘组件在组件Hotels.and中使用,它调用酒店的构造器中的服务函数(以获取数据)。
第一次调用组件时,当我返回到相同的组件时,所有的都是okay.but,它是Figure2中的things.like的两倍
@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代码如下:
<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');
});
}有没有人能给我一个更好的建议?
发布于 2018-04-05 13:38:53
您正在推送现有数组中的最新数据,当您从后端获取更新的数据时,请清除已有的数组。
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));
}https://stackoverflow.com/questions/49663702
复制相似问题