【发布时间】:2019-03-31 23:20:40
【问题描述】:
我有一个角度组件,它显示来自 API 的加密货币价格。在同一个服务中,我为每个组件都有一组硬编码的星级值。当我遍历 API 中的每个值时,我还创建了一个内部 for 循环来遍历对象文字的硬编码数组,并附加唯一的数组值以对每个加密组件进行评级。旧版本(已注释掉)有效,但显示所有加密组件的相同评级信息。现在我将其注释掉并在数组中放入更多值以使其更简单。这是代码。我没有收到任何错误,只有控制台中未定义,并且评级组件停止显示在加密组件中。
getProducts() {
return this.http.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT,TRX&tsyms=USD')
.map(result => {
Object.keys(result).forEach(value => {
// add logic to have each crypto a different rating
var ratings = [{rating: 4, numOfReviews: 2}, {rating:5, numOfReviews: 3}, {rating:6, numOfReviews:1}];
for(var i = 0; i < ratings.length; i++) {
result[value]['ratingInfo'] = ratings[i].rating;
result[value]['ratingInfo'] = ratings[i].numOfReviews;
}
/* result[value]['ratingInfo'] = {
imageUrl: "http://loremflickr.com/150/150?random=1",
productName: "Product 1",
releasedDate: "May 31, 2016",
description: "Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.",
rating: 4,
numOfReviews: 2
}*/
});
return result;
});
}
Crypto.component.ts
import { Component } from '@angular/core';
import { ProductService } from './product.service';
import { RatingComponent } from './rating.component';
@Component({
selector: 'crypto',
styleUrls: ['./app.component.css'],
template: `<h2 class="header">Crypto Price Compare</h2>
<div *ngIf="cryptos">
<div id="crypto-container" *ngFor="let crypto of objectKeys(cryptos)">
<span class="left">{{ crypto }}</span>
<span class="right">{{ cryptos[crypto].USD | currency:'USD':true }}</span>
<br />
<rating
[rating-value]="cryptos[crypto].ratingInfo.rating"
[numOfReviews]="cryptos[crypto].ratingInfo.numOfReviews">
</rating>
</div>
</div>`
})
export class CryptoComponent {
objectKeys = Object.keys;
cryptos: any;
ratings: any;
constructor(private _data: ProductService) {
}
ngOnInit() {
this._data.getProducts()
.subscribe(res => {
this.cryptos = res;
console.log(res);
});
//this.ratings = this._data.getRatings();
console.log(this.ratings);
}
onClick($event){
console.log("Clicked",$event)
}
}
【问题讨论】:
标签: javascript arrays angular for-loop