What is the best way to extract information from an object in Angular in order to calculate a percentage?

As a newcomer, I am still learning how to phrase my questions correctly, so please be patient with me as I seek understanding. I have an object called Firms, and this is the information it contains: https://i.sstatic.net/fTZHK.png

In code, it appears like this:

  export interface Firm {
  name: string
  fullName: string
  ein: string
  crn: string
  email: string
  email2: string
  address: string
  address2: string
  zip: string
  city: string
  country: string
  phone: string
  phone2: string
  type: string
  logo: string
  disabled: true
  taxPayer: true
  locale: string
  currency: string
  domain: string
}

I'm trying to figure out how to retrieve "maxIncomePerYear" or "maxIncomePer365" from the Firms object so that I can perform calculations with them. Here's what I've attempted so far:

export class InsightsComponent implements OnInit {
  insights: any;
  firm:Firm;

  constructor(
    private firmService: FirmService,
    private provider: FirmProvider,
    private http: HttpClient,
  ) {}
  ngOnInit(): void {
    this.provider.getInsights(this.firmService.getDomain())
      .then(data => {
        console.log(data);
        this.insights = data;
      });
    this.provider.getCurrent(this.firmService.getDomain())
      .then(data => {
        this.firm = data;
      });
  }

  calcInvoiced = (firm: number, insights: number) => {
    

 return ((this.firms.maxIncomePerYear / this.insights.incomeForYear) * 100).toFixed(2);
  }
}

Answer №1

Incorrect key being utilized to determine the percentage

calculateInvoicedPercentage = (firm: number, insights: number) => {
    return ((this.firms.maximumIncomePerYear / this.insights.totalIncomeForYear) * 100).toFixed(2);
}

Answer №2

This is the solution I came up with:

class AnalysisComponent implements OnInit {
  data: any;
  company: any;
  

  constructor(
    private companyService: CompanyService,
    private provider: CompanyProvider,
    private http: HttpClient,
  ) {}
  ngOnInit(): void {
    this.provider.getData(this.companyService.getDetails())
      .then(info => {
        console.log(info);
        this.data = info;
      });
    this.provider.getCurrentInfo(this.companyService.getDetails())
      .then(info => {
        this.company = info;
      });
  }

  calculateRevenue = (company: any, data: any, suffix: string): string => {
    if (!company || !data) {
      return '0';
    }  
    return (this.data.incomeForQuarter / this.company.maxIncomePerQuarter * 100).toFixed(2) + suffix;
  }
}

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

In the desktop view, the onClick button requires two clicks to trigger the onClick function, while in the mobile view, it only takes one click as expected

Here are the topics I want to display as buttons: const paperTopics = [ "Teaching Aptitude", "Research Aptitude", "Comprehension", "Communication", "Mathematical Reasoning and Aptitude", ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...

Changing values in a set of text fields activate a reactive form

I am working with a reactive form that has 10 input textboxes. I need to trigger the value change method for only 6 of those input textboxes. To trigger the form changes, I currently use: this.myForm.valueChanges.subscribe(val => { // code here ...

Tips for efficiently reading JSON data on the client side with Angular 2

I received some data that needs to be displayed in HTML. I attempted to call JSON through an API, but unfortunately, it didn't work out. You can view a demo of my code here. Is there another way we can access this data without making an API call? I o ...

"Displaying only the most recent item added to a Typescript array using

After retrieving a list from my API, the data looks like this: { "content": [ { "trainingClassId": 1, "examCode": "my exam 1", "address": { "addressId": 1, "addressValue": "abc 1213" }, "description": "o ...

javascript creating a module to extend a nested object

Currently, I am working on a JavaScript module that includes an object of default options. Here is a snippet of the code: var myModule = function() { // Define option defaults var defaults = { foo: 'bar', fooObject: { option1 ...

Playing with an array of objects

How can we modify an array of objects in Angular Typescript by replacing certain values and adding new key-value pairs? I need to swap the id value with memberId and then introduce a new key fullName that combines firstName and lastName. Any suggestions ...

JavaScript error occurs when the max old space size is enlarged, resulting in an invalid size

Encountering an error while attempting to compute a sha256 hash of a large buffer (~300 MB) using the hash.js library: # # Fatal error in , line 0 # Fatal JavaScript invalid size error 169220804 # # # #FailureMessage Object: 0x7ffd6dc623c0 1: 0xbe6ad1 [/ ...

What approach is most effective for serving static files conditionally in an Express application?

In the process of developing an application, I have decided to create two distinct sections using two individual Angular applications on the frontend. This approach allows me to segregate access control within the codebase, ensuring that team members only ...

What causes the function endpoint to become unreachable when a throw is used?

One practical application of the never type in typescript occurs when a function has an endpoint that is never reached. However, I'm unsure why the throw statement specifically results in this unreachable endpoint. function error(message: string): ne ...

Passing integers as props in Svelte components

Just starting out with Svelte and I'm trying to figure out how to pass a number value as a prop. Here's the code I have so far: <script lang="ts"> import Infobox from "./Infobox.svelte"; </script> <Infobox cl ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...

Encountering the NullInjectorError: No provider for Injector! error repeatedly while attempting to interact with a store

I've been working on a web app that incorporates a store by following this tutorial: . However, I keep encountering the following error: main.ts:13 NullInjectorError: StaticInjectorError(AppModule)[InjectionToken @ngrx/store Initial Reducers -> In ...

The 'type' property is not defined in the current type, however, it is expected in the 'Props' type

https://i.sstatic.net/7bD1N.pngI encountered an unusual typescript error in my IDE on line 16 when I was converting my React ES6 component to TypeScript. The error pertains to a chart component that utilizes react-chartjs-2. The error message states that ...

The error was thrown by the internal module loader in Node.js at line 1029

I encountered this Console Error - "Error: Cannot find module". Below is the detailed error message in the console. Any solutions? node:internal/modules/cjs/loader:1029 throw err; ^ Error: Cannot find module '/home/hiranwj/list' at Mo ...

reinstate dummy of external class method in ts-jest

Problem I am encountering an issue while trying to mock a function that is imported from another class and called within the main class. Although I can successfully mock the function and return the specified values, I am unable to revert the mocked functi ...

Setting the default option in an Autocomplete component using Material UI in React JS

I am currently working with autocomplete input using react material ui component. One specific challenge I am facing is setting a default selected value when a user enters edit mode for this input field. Although I can select the option using getOptionSe ...

Issue with material datepicker not initializing start value when input field is clicked

Using the Material date picker, I've implemented the date picker feature with the startAt binding to establish a default selected value. Users can open the calendar overlay by clicking on the input field, thanks to the (click) and (focus) event bindin ...

Issue with Angular 4: Component refuses to render

Hello, I am currently working with Angular 4 and have implemented various functionalities in different components. Notifications are displayed on the header to inform users of any updates that occur within the app. Each functionality is linked to a corresp ...