我有一个服务文件,该文件返回带有API和数组数据的两个函数。在构造函数的组件内部,我启动一个服务,并尝试在组件中的onInit上检索数据,第一个API函数返回并console.log记录数据,没有问题,但是第二个函数getRatings()
返回console.log中的undefined。为什么?
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);
}
getRatings() {
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
},
{
imageUrl: "http://loremflickr.com/150/150?random=2",
productName: "Product 2",
releasedDate: "October 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: 2,
numOfReviews: 12
},
{
imageUrl: "http://loremflickr.com/150/150?random=3",
productName: "Product 3",
releasedDate: "July 30, 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: 5,
numOfReviews: 2
}];
}
}
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>
</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)
}
}
答案 0 :(得分:3)
在getRatings
服务方法的开头,更改:
getRatings() {
return
[
// ...
收件人:
getRatings() {
return [
// ...
说明:在某些情况下,分号在行尾隐含。在您的情况下,您的代码仅被解释为return;
,而以下代码将被忽略。