首页 > 解决方案 > 我怎样才能修复我的代码,以便我可以读取我的数据

问题描述

运行这段代码(如下)给了我这个错误信息:

TypeError: res.rates.pipe is not a function
    at SafeSubscriber._next (area.component.ts:35)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:185)
    at SafeSubscriber.next (Subscriber.js:124)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at CatchSubscriber._next (Subscriber.js:72)
    at CatchSubscriber.next (Subscriber.js:49)
    at TapSubscriber._next (tap.js:46)
    at TapSubscriber.next (Subscriber.js:49)
    at MapSubscriber._next (map.js:35)
defaultErrorLogger @ core.js:6014 

类型未知的属性 Alloc 不存在

我的组件代码

import { Component, OnInit } from '@angular/core';
import { ChartsModule} from 'ng2-charts/ng2-charts'
import * as Chart from 'chart.js';
import { AreaService } from './area.service';
import { IArea } from './area';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';




@Component({
  selector: 'app-widget-area',
  templateUrl: './area.component.html',
  styleUrls: ['./area.component.scss']
})
export class AreaComponent implements OnInit {

  area:IArea[];  
  httpService: any;
  LineChart: Chart;
  errorMessage:string;
  Date1;
  Alloc;
  constructor(private _areaService:AreaService) { }
   ngOnInit() {
    this._areaService.getArea().subscribe(
     res => {
        this.Alloc = res['rates'].pipe(map(res => res.Alloc))
      })
     this.LineChart = new Chart('lineChart', {
        type: 'line',
        data: { 
           labels: ["2009","2010","2011","2012","2013","2014","2015","2016","2017","2018","2019"],
            datasets: [{
            data: this.Alloc,
            fill:false,
            lineTension:0.2,
            borderColor:"blue",
            borderWidth: 1

          },

        ]

      },

        options: {
          legend:{
            display: false
          },
          scales: {
            xAxes: [{
              display: true
            }],
             yAxes: [{
               display:true
             }]

        }
      }
    })

}
  createChart() {
    throw new Error("Method not implemented.");
  }

} 

我的服务代码:

import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient, HttpErrorResponse} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators'; 
import { IArea } from './area';

@Injectable({
  providedIn: 'root'
})
export class AreaService {



  private areaUrl = 'assets/rates.json'



  constructor(private http: HttpClient) { }

  getArea(): Observable<IArea[]> {
      return this.http.get<IArea[]>(this.areaUrl).pipe(tap(res => res),

          catchError(this.handleError)
        );
    }
    private handleError(err:HttpErrorResponse){
      // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }

}

我的数据只是与年份相对应的数字:

{"rates":[

      {
      "Alloc": 23

      },
      {
      "Alloc": 20
    },
    {
      "Alloc": 30
    },
    {
      "Alloc": 40
    },
    {
      "Alloc": 24
    },
    {
      "Alloc": 23
    },
    {
      "Alloc": 23
    },
    {
      "Alloc": 56
    },
    {
      "Alloc": 32
    },
    {
      "Alloc": 34
    },
    {
      "Alloc": 34
    }
  ]}

尝试使用 map 运行它,但这也不起作用。我已经导入了 rxjs,我不确定如何解决这个问题,所以我的数据被绘制在图表上。

标签: angularrxjschart.js

解决方案


pipe是 Observables 的一种方法,用于链接可观察操作符。在调用之前,您必须在 Observable 上使用它subscribe

在您的情况下,一个普通的 JavaScriptthis.Alloc = res.rates.map((e) => e.Alloc);可能就足够了。


推荐阅读