Kaker
Kaker

Reputation: 645

Array in service not found in method angular 2

hi i have array in servcie and I have a strange problem in the saveData array function is visible but in removeItems no

my service.ts

export class FormService {
  myArray = []
  constructor(){
  }
  saveData(key, value) {
    this.myArray.push({
      key: key,
      value: value
    });
   //HERE IS VISIBLE and i can add may elements
    console.log('myArray')
    console.log(this.myArray)
  }
  removeItems(myIndex) {
    //here is not visible is empty 
    console.log(this.myArray)
  }

}

UPDATE my component

 export class Step3AdditionalServicesComponent implements OnInit {


      constructor(private formService: FormService) {

      }

      ngOnInit() {
        this.stepsGuard.getAccess(false);
      }
      addToMyArray(key,value) {
        this.formService.saveData(key,value)
      }


removeItemFromArray(event) {
    var myIndex = event.target.id;

    console.log('myIndex ' + myIndex);


    this.formService.removeItems(myIndex);
  }
    }

my html

<button (click)="addToMyArray('key1','simple1')">Add Simle1</button>
<button (click)="addToMyArray('key2','simple2')">Add Simle2</button>
<button (click)="addToMyArray('key3','simple3')">Add Simle3</button>

<button id="1" (click)="removeItemFromArray($event)">Remove 1</button>
<button id="2" (click)="removeItemFromArray($event)">Remove 2</button>
<button id="3" (click)="removeItemFromArray($event)">Remove 3</button>

And when i click removeItemFromArray($event) i see index in console

----SOLUTION----
I declare my service in component providers and in app.module my.component

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css'],
  providers: [FormService] <---delete this and will be working
})

@brijmcq Thanks for help

Upvotes: 0

Views: 90

Answers (2)

brijmcq
brijmcq

Reputation: 3418

Most of the time, declare your service in the module level and not in the component level unless you know what you are doing. You are probably getting the wrong data because if you declare it in component level, you will always get a new instance of FormService and the myArray = [] will always be empty.

You probably know what happens next if you access an empty array by index :)

Upvotes: 1

Lucas Andrade
Lucas Andrade

Reputation: 4570

Here is how I remove and add elements in my array:

  elementsArray = []; 

  addElementList(event) {
    let element = event.data;
    if (!this.elementsArray.includes(element)) {
      this.elementsArray.push(element);
      console.log("Elements in array = " + this.elementsArray);
    }
  }

  removeElementList(event) {
    let element = event.data;
    let index = this.elementsArray.indexOf(element, 0);
    if (index > -1) {
      this.elementsArray.splice(index, 1);
      console.log("Elements in array = " + this.elementsArray);
    }
  }

Upvotes: 0

Related Questions