繁体   English   中英

角度打字稿错误:“字符串”类型无法分配给“任何[]”类型

[英]Angular typescript error: Type 'string' is not assignable to type 'any[]'

我提供了一项服务,以从后端获取数据作为预定义的模型,然后将数据调用到我的组件中,但是,在通过Internet进行研究后,我遇到了无法解决的错误。 当我尝试将数据传递到之前声明的空字符串中时,该错误发生在我的组件中。

这是我的服务:

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

正如错误所言,您正在尝试将字符串分配给any的类型,您需要将字符串推入数组,

this.lineChartLabels.push(i.date); 

我猜i.date是一个string ,因为this.lineChartLabels是一个Array<any>您不能为其分配字符串。

最好推送而不是分配:

this.lineChartLabels.push(i.date)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM