Utilizing a TypeScript getter or local variable to reference a service variable within an Angular component

Suppose you have an array of objects stored in a service

export class DataService {

  private _dataSources : Array<DataSource>

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

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

I would like to utilize the array of dataSources within a for loop in a component referred to as "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 real question is, what is the optimal method for implementing the for loop, taking into account:

  • dataSources can potentially contain a large amount of data from multiple sources (similar to an Excel workbook)
  • Code must be easily comprehensible to others

Are there any performance advantages, and what is the standard practice in Angular?

I am aware that

this.dataSources = this.dataService.dataSources();
is simply a reference in memory, so I assume this will not impact performance in any way?

Answer â„–1

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

One advantage of using the dataSources component property is that it leads to slightly better performance. This is because the dataService does not have to be checked on change detection and the dataSources getter function does not need to be called every time.

If the dataService.dataSources is accessed multiple times in the component or its children, using the dataSources component property can help in keeping the code more DRY and readable.

However, in all other aspects, there is no noticeable difference between the two approaches.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance your React Highchart by incorporating gradient shading to the data points

One interesting feature in classic highcharts is the ability to apply gradient coloring to points: Highcharts.setOptions({ colors: Highcharts.getOptions().colors.map(function (color) { return { radialGradient: { cx: ...

JavaScript library experiencing import issues with Typescript custom type

Working on a Vue project with TypeScript, I encountered an issue when importing a custom type created for the vue-numeral-filter package. The error message received is as follows: ERROR in /Users/bmartins/Development/app-invest/src/main.ts(14,30): 14:30 ...

The API code runs smoothly in Angular, but hits a snag when used in Ionic

Here is the API code I used to connect my application to Zoho Creator: <form method="POST" action="https://creator.zoho.com/api/batool4/xml/myapp/form/form1/record/add"> <input type="hidden" name ="authtoken" value="14e8d1c6acf83682cd9622986f0f7 ...

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...

Exploring TypeScript to get a ref with the Vue Composition API

The issue I'm facing is related to Vetur underlining 'null' in the following line: const firstRef = ref<HTMLElement>(null) <template> <input id="first" ref="firstRef"> <button type="button&q ...

What's Causing the UNMET PEER DEPENDENCY Error in Angular 8 with @angular/[email protected]?

After updating to the latest version of Angular 8, everything seems to be working fine without any issues. However, I am seeing some strange messages when running npm list after completing npm install: UNMET PEER DEPENDENCY @angular/<a href="/cdn-cgi/ ...

Is there a way to selectively deactivate the routerLink attribute?

I am facing a challenge in my Angular 2 project where I am unable to disable the routerLink functionality successfully. Despite trying to intercept the click event on the 'click' event with 'event.preventDefault()' and 'event.stopP ...

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...

Controlling a generic interface's acceptance of certain data types in typescript: a guide

Is there a way to restrict a generic interface from accepting specific data types in TypeScript? I understand that I can define acceptable data types for a generic interface in TypeScript. interface exampleInterface<T = void | any>; But what if I w ...

Is there a way to go back to the previous URL in Angular 14?

For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action. ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Combining Angular 2 and Sails.js for Ultimate Web Development

Looking to integrate Sails with Angular 2 and add TypeScript to my project. As a newcomer in this field, I'm unsure how to configure this. I have created a Sails app using the command: sails new myApp Could anyone guide me on how to incorporate thi ...

Even when it appears to be chaotic, the TypeScript array of numbers always manages to find its way back to being sorted

I recently developed a function that aims to verify if an array of numbers is sorted: const checkIfSorted = (numbers: number[]) => { return numbers === numbers.sort((a, b) => a - b); }; checkIfSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // This cur ...

Can you explain the distinction between angular-highcharts and highcharts-angular?

Our team has been utilizing both angular-highcharts and highcharts-angular in various projects. It appears that one functions as a directive while the other serves as a wrapper. I'm seeking clarification on the distinctions between the two and recomme ...

Ionic 4 does not support the command 'ionic package build ios development'

Struggling to make sense of the ionic 4 documentation, I attempt to build an iOS app on Windows using 'ionic package build ios'. Can this be done? Attempting to create an iOS app with ionic 4 using 'ionic package build ios'. ionic pac ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

Obtain the data from a promise in Angular

I have a function that returns a Promise, and within that Promise, I receive an object in the resolve. Below is the function from my service that is functioning correctly. buscarUsuario(email: string){ return new Promise((resolve, reject) => { this.ht ...