Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a typescript getter or local variable for a service variable in Angular component

So let's say you have an array of objects in a service

export class DataService {

  private _dataSources : Array<DataSource>

  contructor(private callerService: CallerService){
    this._dataSources = this.callerService.getDataSources(); // getting data from another service
  }

  // getter for _dataSources
  get dataSources(): Array<Datasource> {
    return this._dataSources;
  }
}

I want to use the array of dataSources in the for loop of an component that we shall call "DataComponent"

@Component({
  selector: 'data-component',
  template: `
       <div *ngFor="let dataSource of dataService.dataSources"></div> // one way
       <div *ngFor="let dataSource of dataSources"></div> // other way
     `,
  styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {

  public dataSources: Array<DataSource>

  constructor(public dataService: DataService) { }

  ngOnInit() { 
   this.dataSources = this.dataService.dataSources(); 
  }

So the question here is, what is the best way of doing the for loop, considering:

  • DataSources can be a very large object of multiple datasheets (like an excel workbook)
  • Code must be easily understandable by others

Are there any performance benefits, what is common practice in Angular?

I know that this.dataSources = this.dataService.dataSources(); is actually just a pointer in memory so this will not cause any performance differences I guess?

like image 425
Sytham Avatar asked Sep 12 '26 06:09

Sytham


1 Answers

<div *ngFor="let dataSource of dataSources"></div>

is negligibly more performant because dataService doesn't need to be checked on change detection, dataSources getter function doesn't need to be called every time.

If dataService.dataSources is used more than once in the component or its children, dataSources component property allows to keep the code a bit DRYer and more readable.

In other aspects there's no difference.

like image 78
Estus Flask Avatar answered Sep 14 '26 18:09

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!