我提供服务以从后端获取数据作为预定义模型然后我将数据调用到我的组件中,但是,我得到了在互联网上进行研究后无法解决的错误。当我尝试将数据传递到我之前声明的空字符串时,错误发生在我的组件中。
这是我的服务:
import { Observable } from 'rxjs/Observable';
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ORIGIN_URL, API_PREFIX } from '../shared/constants/baseurl.constants';
import { History } from '../models/history';
import 'rxjs/add/operator/map';
@Injectable()
export class HistoricalBpiService {
private apiUrl: string;
constructor(
private http: Http,
@Inject(ORIGIN_URL) private baseUrl: string,
@Inject(API_PREFIX) private apiPrefix: string
) {
this.apiUrl = baseUrl + apiPrefix;
}
oneYear(): Observable<History[]> {
return this.http.get(this.apiUrl + 'data/history/365')
.map((res: Response) => res.json() as History[])
.catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
这是模型:
export interface History {
date: string;
value: number;
}
这是组件:
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { History } from '../../models/history';
@Component({
selector: 'app-banner',
templateUrl: './banner.component.html',
styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {
history: History[] = [];
public lineChartData: any = [
{ data: [], label: 'BTC' }
];
public lineChartLabels: Array<any> = [];
constructor(
private historicalBpiService: HistoricalBpiService,
@Inject(PLATFORM_ID) private platformId: Object
) {}
oneYear() {
this.historicalBpiService.oneYear()
.subscribe((data: History[]) => {
this.history = data;
for (let i of this.history) {
this.lineChartData[0].data = i.value;
this.lineChartLabels = i.date; // THIS LINE CAUSES ERROR !!!
}
});
}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
// Default chart
this.oneYear();
}
}
}
答案 0 :(得分:1)
如错误所示,您正在尝试将字符串分配给任何类型, 您需要将字符串推送到数组
this.lineChartLabels.push(i.date);
答案 1 :(得分:1)
我猜测i.date
是string
,因为this.lineChartLabels
是Array<any>
,您无法为其分配字符串。
最好推,而不是分配:
this.lineChartLabels.push(i.date)