简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM