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

标签 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 get 请求和同一服务中评级数据的硬编码数组数据,然后从 crypto.component.ts 中的数组访问评级数据里面<rating>选择器没有得到未定义的错误?现在看起来像这样:

enter image description here

抱歉,如果解释不清楚,我只是想将星级评分系统添加到显示来自服务的数据的组件,该服务正在从 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>

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

关于javascript - 如何在 Angular 2 的同一服务中将一些硬编码数据与 API 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998461/

相关文章:

javascript - 从对话框中获取值并在后面的代码中使用它们

javascript - 使用 HIGHCHARTS (xAxis dateTime) 添加点

javascript - 以不可变的方式过滤作为对象属性的数组

angular - Electron:错误:由于版本无效或不受支持,无法反序列化克隆数据

html - 如何为每个容器创建不同的滚动条

javascript - React-Router ^2.4.0 错误。亲属路线找不到元素

javascript - 如何使用 jQuery/Javascript 将事件从一个选项卡/窗口发送到另一个选项卡/窗口

javascript - 单击保存时 Angular Material 对话框传递动态功能

css - 如何在 Angular 5 中为 typescript 中的字符串添加颜色

angular - 在 Angular 4/5 中编译动态 HTML——类似于 Angular JS 中的 $compile