Ruben Martinez
Ruben Martinez

Reputation: 35

not able to assign data from service to array

Have this component:

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('datos invalidos');
      return;
    }
  }
}

I see data coming from the service but nothing is on the arrays typos and areas. Can anyone help me to understand if there is anything wrong.

Upvotes: 0

Views: 62

Answers (1)

KShewengger
KShewengger

Reputation: 8269

That is because you are consoling your tipos and areas outside your subscription.

You need to console inside of your subscriptions to check their values:

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

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

NOTE:

  • Subscriptions from your service calls are dealing with Observables which they needed to be subscribe first before you'll be able to fetch their respective response

Upvotes: 1

Related Questions