Javascript 如何在Anglular 2中的同一服务中使用一些硬编码数据和API?

Javascript 如何在Anglular 2中的同一服务中使用一些硬编码数据和API?,javascript,angular,angular5,angular-services,angular-components,Javascript,Angular,Angular5,Angular Services,Angular Components,我有一个从API中检索数据并在我的组件中显示的服务。一切都很好,但是除了我在组件中显示的API中的数据外,我还想在同一组件中显示来自同一服务的一些硬编码数组数据。(硬编码数据实际上会显示在另一个组件中,然后嵌套在我用来显示API数据的组件中。) 服务: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { HttpClientModule }

我有一个从API中检索数据并在我的组件中显示的服务。一切都很好,但是除了我在组件中显示的API中的数据外,我还想在同一组件中显示来自同一服务的一些硬编码数组数据。(硬编码数据实际上会显示在另一个组件中,然后嵌套在我用来显示API数据的组件中。)

服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import 'rxjs/Rx';


@Injectable()
export class ProductService{
  result:any;
  ratings:any;
  constructor(private http: HttpClient) {}
    getProducts() {
        return this.http.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT,TRX&tsyms=USD').map(result => this.result = result);
        /*return
           [
            {
                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
            },
正如您在返回后看到的,我对数组进行了一些注释。我正在使用
评级
组件:

import { Component, Input } from '@angular/core'

@Component({
    selector: 'rating',
    templateUrl: 'rating.component.html',
    styles: [`
        .glyphicon-star {
            color: blue;
        }
    `]
})
export class RatingComponent{

    @Input('rating-value') rating = 0;
    @Input() numOfReviews = 0;

    onClick(ratingValue){
        this.rating = ratingValue;
    }
}
import { Component } from '@angular/core';
import { ProductService } from './product.service';
import { RatingComponent } from './rating.component';
@Component({
  selector: 'crypto',
  styleUrls: ['./app.component.css'],
  template: `<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]="rating"
          [numOfReviews]="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);

    });
}

    onClick($event){
      console.log("Clicked",$event)
    }
}
然后我想在crypto component中显示带有来自服务的数组数据的评级组件:

import { Component, Input } from '@angular/core'

@Component({
    selector: 'rating',
    templateUrl: 'rating.component.html',
    styles: [`
        .glyphicon-star {
            color: blue;
        }
    `]
})
export class RatingComponent{

    @Input('rating-value') rating = 0;
    @Input() numOfReviews = 0;

    onClick(ratingValue){
        this.rating = ratingValue;
    }
}
import { Component } from '@angular/core';
import { ProductService } from './product.service';
import { RatingComponent } from './rating.component';
@Component({
  selector: 'crypto',
  styleUrls: ['./app.component.css'],
  template: `<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]="rating"
          [numOfReviews]="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);

    });
}

    onClick($event){
      console.log("Clicked",$event)
    }
}
从'@angular/core'导入{Component};
从“./product.service”导入{ProductService};
从“/rating.component”导入{RatingComponent};
@组成部分({
选择器:“加密”,
样式URL:['./app.component.css'],
模板:`
{{crypto}}
{{cryptos[crypto].USD |货币:'USD':true}

` }) 导出类加密组件{ objectKeys=Object.keys; 密码:任何; 评级:任何; 构造函数(私有数据:ProductService){ } 恩戈尼尼特(){ 这是。_data.getProducts() .订阅(res=>{ this.cryptos=res; 控制台日志(res); }); } onClick($event){ console.log(“Clicked”,$event) } }
类似这样的,但不起作用:

<rating
      [rating-value]="rating"
      [numOfReviews]="numOfReviews">
</rating>

我如何从API返回HTTP get请求和同一服务中评级数据的硬编码数组数据,然后从
crypto.component.ts
选择器中的数组访问评级数据,而不获得未定义的错误?现在看起来是这样的:


很抱歉,若解释不清楚,我只是尝试将星级系统添加到一个组件,该组件显示来自服务的数据,该服务从API获取数据。API仅提供加密名称和价格。星级组件的数据将在阵列内部自行硬编码。

产品服务如下:

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

      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;
  });
<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>
然后按如下方式更新加密组件:

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

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

{{crypto}}
{{cryptos[crypto].USD |货币:'USD':true}


有更好、更干净的方法来实现您想要的,但需要对代码进行一些重构。

谢谢,它可以工作。但是我不知道
['ratingInfo']
是从哪里来的?
['ratingInfo']
是动态创建的,如果
result[value]
处的对象没有名为'ratingInfo'的属性,那么Javascript会创建这个新属性,并将评级对象
{imageUrl:}……
分配给它(你可以说像1中的两个步骤)