使用服务文件保存数据 angular

Save the data get using service file angular

我正在尝试在 angular 中创建图表并使用服务获取数据。我想使用从这里获取的数组数据。 pieData: 任意 = []; 构造函数内的控制台正确显示数据。但是 ngOnInit 中的控制台显示空数组。

import { Component, OnInit } from '@angular/core';
import { PieChartService } from './pie-chart.service';
@Component({
  selector: 'app-pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css']
})
export class PieChartComponent implements OnInit {
  pieData: any = []; 

  constructor(private PieChart: PieChartService) {
    this.PieChart.getMethod().subscribe((res: any) => {
      this.pieData = res.pieData;
      console.log(this.pieData);
    })
  }
  ngOnInit() { }
 //code for create a graph here
}

您可以尝试将订阅移动到 ngOnInit 挂钩中,这样您就可以编写代码或调用从订阅内部创建图表的函数。虽然我不确定为什么你需要在构造函数中订阅,但我会说在构造函数内部工作不是最佳实践,因为它主要用于初始化 class 成员。而在初始化组件的所有数据绑定属性后调用 ngOnInit。

也引用

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

您的问题的解决方案是:

pieData$: Subscription; // subscription for data
ngOnInit() { 
  this.pieData$ = this.PieChart.getMethod().subscribe((res: any) => {
    this.pieData = res.pieData;
    console.log(this.pieData);
    //code for create a graph here
  })
}

另外不要忘记取消订阅 Destroy

ngOnDestroy() {
  this.pieData$.unsubscribe();
}

备选方案:使用 Promise

pie-component.ts

import { Component, OnInit } from '@angular/core';
import { PieChartService } from './pie-chart.service';

@Component({
    selector: 'app-pie-chart',
    templateUrl: './pie-chart.component.html',
    styleUrls: ['./pie-chart.component.css'],
})
export class PieChartComponent implements OnInit {
    pieData: any = [];

    constructor(private PieChart: PieChartService) {
        console.log('[PieChartComponent]', '[constructor]');
    }

    async ngOnInit() {
        console.log('[PieChartComponent]', '[OnInit]');
        // Follwoing promise is `await`-ed, so execution proceeds once that finishes,
        // and after which this.pieData will be set and can be accessed for values 
        // from anywhere else in the component's lifecycle hooks or any other operations 
        // that it supports. Enclose within a try-catch for error handling
        const pieDataResponse = await this.PieChart.getMethod().toPromise();
        this.pieData = pieDataResponse?.pieData || [];
        console.log('[PieChartComponent]', '[pieData]', '[Received]', this.pieData);
        //code for create a graph here
    }
}

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET