unable to populate the array with information retrieved from the service

Here's a snippet of code for a component in Angular:

import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup, NgForm } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { CisvcService } from 'src/app/services/cisvc.service';

@Component({
  selector: 'app-cambio',
  templateUrl: './cambio.component.html',
  styleUrls: ['./cambio.component.css']
})
export class CambioComponent implements OnInit {
  idproyecto: any;

  tipos: any[] = [];
  areas: any[] = [];
  cbAreas: boolean[] = [];

  constructor(private activatedRoute: ActivatedRoute, private svc: CisvcService ) {}

  ngOnInit(): void {

    this.activatedRoute.params.subscribe( params => {
      this.idproyecto = params['id'];
    });

    this.svc.getTipos().subscribe( (data: any[]) => {
      console.log(data);
      this.tipos = data;
    });

    this.svc.getAreas().subscribe( (data: any[]) => {
      this.areas = data;
    });

    console.log(this.areas);
    console.log(this.tipos);

  }

  formSubmit( forma: NgForm ){
    if (forma.invalid){
      console.log('invalid data');
      return;
    }
  }
}

I am encountering an issue where data is being received from the service but is not populating the arrays `typos` and `areas`. Any insight on what might be causing this would be greatly appreciated.

Answer №1

One reason for this could be that you are consoling your tipos and areas outside of your subscription.

To properly check their values, make sure to console inside of your subscriptions like this:

this.svc.getTipos().subscribe( (data: any[]) => {
  this.tipos = data;
  console.log(this.tipos);              // Log the value here
});

this.svc.getAreas().subscribe( (data: any[]) => {
   this.areas = data;
   console.log(this.areas);            // Log the value here
});

PLEASE NOTE:

  • Remember, when dealing with Observables in your service calls, they need to be subscribed first before you can access their responses.

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

New Requirement for Angular Service: Subclass Constructor Must Be Provided or Unable to Resolve all Parameters for ClassName (?)

During a recent project, I encountered an issue while working on several services that all extend a base Service class. The base class requires a constructor parameter of HttpClient. When setting up the subclass with autocomplete, I noticed that their con ...

Guidelines on encoding query parameters for a tRPC query with the fetch function

As stated in the tRPCs official documentation, the query parameters must adhere to this specific format: myQuery?input=${encodeURIComponent(JSON.stringify(input))} Here is an example of a procedure: hello: publicProcedure .input(z.object({ text: z.s ...

Utilizing TypeScript interfaces to infer React child props

How can I infer the props of the first child element and enforce them in TypeScript? I've been struggling with generics and haven't been able to get the type inference to work. I want to securely pass component props from a wrapper to the first ...

Navigating through Angular2 Components: Form validation fields access in Component.ts

Suppose I have a form that does not use FormGroup, and the view appears as follows: <form #f="ngForm" novalidate> <label>Email</label> <input type="email" [(ngModel)]="player.email" class="form-control" name="email" #email=" ...

Encountering an Angular 9 Ivy issue when using the <mat-form-field> with multiple mat-hints

After migrating to angular9 Ivy, I encountered an issue with multiple mat-hints in a single component. Before the update, my code looked like this: <div class="example-container"> <mat-form-field hintLabel="Max 10 characters" ...

Modify the [src] attribute of an image dynamically

I have a component that contains a list of records. export class HomeComponent implements OnInit { public wonders: WonderModel[] = []; constructor(private ms: ModelService){ ms.wonderService.getWonders(); this.wonders = ms.wonder ...

Angular 6 is throwing a StaticInjectorError within the AppModule window

Is there a way to access an Excel file from a specific location through the window? constructor( private fb: FormBuilder, private http: Http, private router: Router,private window:Window) { } window.open(this.excelURL + "report/" + this.getexportlist.dat ...

Step-by-step guide on generating a numpy array while iterating through a loop

I currently have a numpy list that contains arrays (a two-dimensional list): db = [ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10, ch11, ch12, ch13, ch14, ch15, ch16] My goal is to apply operations to these arrays as shown below: for i in db: new ...

Using ADAL with ASP.NET MVC and Angular for Seamless Login Experience

Currently, we have an ASP.NET MVC application in place but are looking to incorporate Angular for new frontend functions and gradually transition the entire frontend to Angular. However, at this stage, we are facing a challenge where user logins are only b ...

Instructions for utilizing a Boolean array or LogicalVector in Rcpp list to retrieve the PIC value can be found in the function `getPIcvalue()` within the R package. Additionally,

While attempting to install the mypackage5 package using RcppEigen.package.skeleton(), I encountered an issue with the LogicalVector& in both the Rcpp::List getPIcvalue and RcppExport SEXP mypackage5_getPIcvalue functions. Below is a C++ function featu ...

What is the best way to use a generic callback function as a specific argument?

TS Playground of the problem function callStringFunction(callback: (s: string) => void) { callback("unknown string inputted by user"); } function callNumberFunction(callback: (n: number) => void) { callback(4); // unknown number inputt ...

How can I avoid using "data.*" in the Angular Material dialog template?

I have a template similar to the one provided below: card.component.html <mat-card class="mat-elevation-z4"> <img mat-card-image src="{{ item.media_url }}" /> <mat-card-content class="custom"> <p& ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

What is the reason behind Jest v24 mocking classes that have a need for private methods

Currently, I am facing a challenge in creating mock implementations of my Typescript classes using Jest v24+. Specifically, I am trying to create a mock class that will be injected into a constructor and mock the functions to return specific responses. My ...

Create an array of distinct expressions by grouping consecutive words based on the number of words

Currently, I am working on setting up a word search feature using PHP's explode() function to separate words and determine the number of spaces in a query. For instance, if a user submits the query Hello world, good morning The output would be: hel ...

What is the best way to persist form state in an Angular Lazy Loading Module?

I've set up 2 routes in my Angular 7 application, { path: 'create', component: CreateComponent }, { path: 'view', component: ViewComponent } Both of these routes are lazily loaded. The CreateComponent contains a f ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

Learn the process of adding data to an array through ajax requests

Is there a way to populate an array with offerIds from multiple products listed on a page by clicking the add to cart button? I am currently using the data attribute in the button to push the offerId string into the array, but only the latest offerId is be ...

Struggled to incorporate Typescript function overload's implementation

After reviewing the previous question: Typescript: exclude undefined/null properties from type In my TypeScript project, I attempted to create an overload for a function called request, which can optionally accept a payload. The function is defined by the ...

Guide to creating a setter for an array property in Angular 2 (Typescript) that will be filled by the view

Question: private _secretQuestions: {question: number, answer: string}[]; Within my HTML, I have three select boxes representing questions, each with a corresponding input box for answers. My goal is to map the selected questions and input values to the ...