从Angular 4 observable格式化chart.js的JSON数据

时间:2017-10-23 21:52:38

标签: json angular typescript chart.js

我一直对此疯狂,无法解决这个问题。我的API数据格式如下:

 "data": [
    {
        "sr_count": 91,
        "month_name": "October",
        "month_num": 10,
        "year": 2017
    },
    {
        "sr_count": 50,
        "month_name": "September",
        "month_num": 9,
        "year": 2017
    }
]

我需要从" sr_count"中获取数据。和" month_name"重新格式化为自己的数组,以便chart.js传递数据。

例如:

["91","50"] 
["October", "September"]

我有一个 reportService ,它正在从我的API中获取数据

  getSR(groupBy: string, beginDate:string, endDate:string): Observable<Report[]> {
    return this.http.get(`${this.reportUrl}/SR?group_by="${groupBy}"&begin_date="${beginDate}"&end_date="${endDate}"`)
      .map(res => res.json().data)

      .catch(this.handleError);
  }

从我的组件代码中我发现我可以将sr_countmonth_name中的所有数据映射到数组中,然后将其推送到局部变量中,以便我可以在chart.js的数据

export class SrReportsComponent implements OnInit {
    monthName: [];
    srCount1: [];
    srCount2: [];
    data: any;

ngOnInit() {
 this.reportService.getSRLastMonth()
        .subscribe(data => {

            srCount= data.map(item => {
                return item.sr_count
            })


            console.log(srCount) // ["October", "September"]

            this.srCount2.push(srCount) // [["52", "41"]]



        });
    this.reportService.getSRThisMonth('Month',lastMonth,today)
        .subscribe(data => {

            monthName= data.map(item => {
                return item.month_name
            }
            srCount= data.map(item => {
                return item.sr_count
            }


            console.log(monthName) // ["October", "September"]

            this.monthName.push(monthName) // [["October", "September"]]
            this.srCount1.push(srCount) //[["91","50"]]


        });
        console.log(this.monthName)// [["October", "September"]]



        this.data = {
            labels: this.monthName, //returns []
            datasets: [
                {
                    label: 'First Dataset',
                    data: this.srCount1,
                    fill: false,
                    borderColor: '#4bc0c0'
                },
                {
                    label: 'Second Dataset',
                    data: this.srCount2,
                    fill: true,
                    borderColor: '#4ba0c0'
                }

            ]
        }
}

因为使用push()方法,它似乎正在嵌套我的数组,而chart.js无法看到。我也尝试了monthName[0]并在控制台中获取了undefined

将observable中的数组传递给局部变量的最佳方法是什么,以便我可以使chart.js工作?

2 个答案:

答案 0 :(得分:0)

如果你需要的只是不#34;筑巢&#34;月份名称数组可以使用array.push.apply(array,array2)方法(参见下面的链接)。

所以你的阵列:

public class someFragmentClass extends Fragment {

    Timer mTimer;
    View mView;

    TimerTask timerTask = new TimerTask(){
        @Override
        public void run() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                       randomMovement(img);
                    }
                }
            });
        }

    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
       Bundle savedInstanceState) {

       mView = inflater.inflate(R.layout.someFragment, container, false);

       mTimer = new Timer();
       mTimer.scheduleAtFixedRate(timerTask, 0 , 5000);

       return mView;
    }

}

https://stackoverflow.com/a/4156156/4219717

答案 1 :(得分:0)

只需将data移到您的观察中。您正在使用异步操作。

 ngOnInit() {
        this.reportService.getSR('Month',lastMonth,today)
            .subscribe(response => {        
            this.data = {
                labels: response.map(item => { return item.month_name });
                datasets: [
                    {
                        label: 'First Dataset',
                        data: this.srCount,
                        fill: false,
                        borderColor: '#4bc0c0'
                    }
                ]
            }
            });

    }