0

I have an @Injectable class with a get-function in Service.ts create. This function should return one Array and also get any array. But it returns null. If I write this directly in a @Component, then it does get the array. What am I doing wrong?

service.ts

@Injectable()
export class Arr_selected {
  private arr = [];
  get(arr_selected: any[]){
      for(let key in arr_selected) {
          if (arr_selected.hasOwnProperty(key)) {
              this.arr.push([key]);
              return this.arr;
          }
      }
      console.log(this.arr);

  }

} 

component.ts

import {Arr_selected} from './service.ts';
export class Component implements DoCheck, OnChanges, OnInit {
....
constructor( public arr_selected: Arr_selected)
.....

ngOnInit{

     let chk = this.ChkBoxValue;

     let arr = [];

/// **this not working Array is null**/////
     arr=(this.arr_selected.get(this.ChkBoxValue));

/// **this is working Array is not null**////
     for (let key in this.ChkBoxValue) {
            if (this.ChkBoxValue.hasOwnProperty(key)) {
              arr.push(this.ChkBoxValue[key]);
         }
       }
        console.log(arr); 
}}
ran
  • 1
  • 3

2 Answers2

0

i thinks below should work

@Injectable()
export class Arr_selected {
      get(arr_selected: any[]){
          arr = [];
          for(let key in arr_selected) {
              if (arr_selected.hasOwnProperty(key)) {
                  arr.push([key]);
                  return this.arr;
              }
          }
          console.log(this.arr);

      }

I think the "this" operator is causing the problem for you . You have arr also defined in the component . this might be conflicting which arr to use.

Bhabani Das
  • 380
  • 5
  • 13
  • Thanks, but it's not working, without 'this' I get an error. – ran May 12 '17 at 18:23
  • you have to move the arr[] to inside the function as shown in my code. If you you leave it as a class variable then you have to keep this. – Bhabani Das May 12 '17 at 18:50
0
Above code you have written your file name as service.ts

and importing from ./servece.ts

   import {Arr_selected} from'./servece.ts;

May be its typing error here , also are you adding your service in provider of component ?.

vaibhavmaster
  • 659
  • 6
  • 10
  • Thanks, I written correct, it was typing error )) --> " import {Arr_selected} from './service.ts'; " I'm adding with providers: [ Arr_selected] – ran May 12 '17 at 19:48