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

时间:2018-10-25 21:37:11

标签: javascript angular angular5 angular-services angular-components

我有一个从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
            },

返回后您可以看到,我对数组进行了注释。我正在使用rating组件:

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

类似这样的东西,但是不起作用:

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

如何从API和硬编码的数组数据返回HTTP获取请求以获取同一服务中的评分数据,然后从crypto.component.ts选择器中的<rating>中的数组访问评分数据而不会出现未定义的错误?现在看起来像这样:

enter image description here

很抱歉,如果解释不清楚,我只是想将星级评分系统添加到一个组件,该组件显示来自服务的数据,该服务从API获取数据。 API仅提供加密名称和价格。星级评分组件的数据将由我自己在数组内进行硬编码。

1 个答案:

答案 0 :(得分:1)

产品服务如下:

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>

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