Reputation: 1170
I make a service to get data from back-end as the pre-defined model then I call the data into my component, however, I got the error that I could not solve it after doing research on the Internet. The error happens in my component when I try to pass data into an empty string that I declared before.
This is my service:
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);
}
}
This is the model:
export interface History {
date: string;
value: number;
}
This is the component:
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();
}
}
}
Upvotes: 0
Views: 3232
Reputation: 2244
I'm guessing that i.date
is a string
, because this.lineChartLabels
is an Array<any>
you can't assign a string to it.
Best to push instead of assign:
this.lineChartLabels.push(i.date)
Upvotes: 1
Reputation: 222582
As the error says, you are trying to assign a string to the type of any, You need to push the string to the array,
this.lineChartLabels.push(i.date);
Upvotes: 2