Javascript 如何使每个角度分量具有不同的数组值

Javascript 如何使每个角度分量具有不同的数组值,javascript,arrays,angular,for-loop,Javascript,Arrays,Angular,For Loop,我有一个显示API加密货币价格的角度组件。在同一个服务中,我为每个组件都有一个硬编码的星级值数组。当我循环使用API中的每个值时,我还创建了一个inside for循环来迭代对象文本的硬编码数组,并为每个加密组件的评级附加唯一的数组值。旧版本被注释无效,但显示了所有加密组件的相同评级信息。现在我将其注释掉,并在数组中添加更多值以使其更简单。这是代码。我没有得到任何错误,只有控制台中未定义的和评级组件停止显示在加密组件中 getProducts() { return this.ht

我有一个显示API加密货币价格的角度组件。在同一个服务中,我为每个组件都有一个硬编码的星级值数组。当我循环使用API中的每个值时,我还创建了一个inside 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;
  });
}
加密组件

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)
    }
}

不确定你到底想做什么,但这没有意义

result[value]['ratingInfo'] = ratings[i].rating;
result[value]['ratingInfo'] = ratings[i].numOfReviews;
您正在设置ratingInfo并立即用其他内容覆盖它。假设ratingInfo是一个对象,您可能需要如下内容:

result[value]['ratingInfo']['rating'] = ratings[i].rating;
result[value]['ratingInfo']['numOfReviews'] = ratings[i].numOfReviews;
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class ProductService {

  constructor(private http: HttpClient) { }
  ...
  getProducts() {

    const ratings = [
      { rating: 4, numOfReviews: 2 }, 
      { rating: 5, numOfReviews: 3 }, 
      { rating: 6, numOfReviews: 1 },
      { rating: 7, numOfReviews: 4 }
    ];

    return this.http.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT,TRX&tsyms=USD')
      .pipe(
        map(
          cryptos => {
            const currencies = [];
            let index = 0;
            return Object.keys(cryptos).map((cryptoName, index) => {
              return {
                name: cryptoName,
                price: cryptos[cryptoName].USD,
                ratingInfo: { ...ratings[index] }
              }
            });
          }
        )
      )
  }
  ...
}
或者更简单地说:

result[value]['ratingInfo'] = ratings[i]

您可能希望更改ProductService的实现,如下所示:

result[value]['ratingInfo']['rating'] = ratings[i].rating;
result[value]['ratingInfo']['numOfReviews'] = ratings[i].numOfReviews;
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class ProductService {

  constructor(private http: HttpClient) { }
  ...
  getProducts() {

    const ratings = [
      { rating: 4, numOfReviews: 2 }, 
      { rating: 5, numOfReviews: 3 }, 
      { rating: 6, numOfReviews: 1 },
      { rating: 7, numOfReviews: 4 }
    ];

    return this.http.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT,TRX&tsyms=USD')
      .pipe(
        map(
          cryptos => {
            const currencies = [];
            let index = 0;
            return Object.keys(cryptos).map((cryptoName, index) => {
              return {
                name: cryptoName,
                price: cryptos[cryptoName].USD,
                ratingInfo: { ...ratings[index] }
              }
            });
          }
        )
      )
  }
  ...
}
这样做将导致getProducts方法返回一个对象数组,您可以在视图中简单地循环

在CryptosComponent模板中,您可以执行以下操作:

<h2 class="header">Crypto Price Compare</h2>
  <div *ngIf="cryptos">
  <div id="crypto-container" *ngFor="let crypto of cryptos">
    <span class="left">{{ crypto.name }}</span> - 
    <span class="right">{{ crypto.price | currency:'USD' }}</span>
    <br />
    <rating
      [ratingValue]="crypto.ratingInfo.rating"
      [numOfReviews]="crypto.ratingInfo.numOfReviews">
    </rating>
  </div>
</div>
注:

我已将rating value的名称更改为ratingValue。 此示例使用Angular 7,其中需要应用于可观察对象的任何操作符都需要通过管道操作符。如果您使用的是Angular 4或Angular 5,则需要使用与现在相同的方法,将.map链接到可观察值。
这里有一个供您参考的选项。

您的选项都不起作用。如果,我正在覆盖它,那么为什么被注释掉的部分正在工作而没有被覆盖?我用加密组件代码更新了我的问题,使之更具意义。它现在运行得很好。我只需要弄清楚如何循环使用更多的评级选项,而不仅仅是为每个API调用值指定一个和唯一的评级信息。是的,我把它改成了不覆盖。我甚至用硬编码的数字来赋值,而不是在数组中循环,但我仍然得到core.js:1673 ERROR-TypeError:cannotset属性“rating”of undefined这个错误听起来就是这样的。看看core.js中的1673。您需要找出调用的原因。对未定义的内容进行评级。我不明白['ratingInfo']在分配对象文字的一个硬编码值时不是未定义的,而是在迭代时从数组中分配评级值时未定义的。嘿,抱歉,响应太晚了。谢谢你这么详细的回答。不幸的是,我无法绑定到“ratingValue”,因为它不是“rating”的已知属性。错误我不明白你所说的评级信息是什么意思:{…评级[索引]}那些是什么。。。?如果我删除它,我的IDE会显示语法错误,我的错误,我的代码中有输入错误,从ratingValue更改为ratingValue。谢谢你的示例代码!