0

I'm trying to initialise Arrays variables from another Array in Angular2. Let me explain in details. Once I load my page, I receive from my server an Arrays containing strings (let's call it initialArray). And I would like to initialise Arrays variables (which I can use for after in my component), which are empty and which i can call for use after. I would like initialArray.length number of arrays. I don't know how can I achieve that

mycomponent.ts

import {Component} from '@angular/core' ;
import {getArrayService} from 'getarray.service';

@Component({
   selector : 'mycomponent',
   moduleId: module.id,
   templateUrl: 'mycomponent.component.html'
})

export class myComponent{

initialArray : Array<string>

constructor(private _getarrayservice : getArrayService)

ngOnInit(){
this._getarrayservice.getArrayfromAPI()
  .subscribe ( res => this.array = res,
              err => console.error(err.status)
            );

for(let name in initialArray ){
   name : Array<any>;
   };

 }
}

However, this code isn't working because name is an array...

Antoine
  • 1
  • 1
  • 6

1 Answers1

0

Try Below

  1. Your constructor lacks the body
  2. initialize your array to a default empty array
  3. make sure your server returns an array of strings, most return json. Otherwise use any instead of string.
  4. Once you have received your server array from the observable the overwrite your initialArray otherwise you can iterate it and push new items to the array if you will.

Sample

import {Component} from '@angular/core' ;
import {getArrayService} from 'getarray.service';

@Component({
   selector : 'mycomponent',
   moduleId: module.id,
   templateUrl: 'mycomponent.component.html'
})

export class myComponent{

initialArray: Array<string> = [];

constructor(private _getarrayservice : getArrayService) {
}

ngOnInit(){
this._getarrayservice.getArrayfromAPI()
  .subscribe ( 
    res => this.initialArray= res,
    err => console.error(err.status)
  );
}
Evans M.
  • 1,791
  • 16
  • 20