Steffn
Steffn

Reputation: 295

How to get access to object, angular 4

I have this array in my DataComponent and want to inject 'string4' to my ConsumeComponent via a Service:

export class DataComponent {
  mystring: string = '';

  constructor(private myService: myService) {}

  data = [
    {
      string1: '',
      string2: '',
      string3: '',
      string4: ''
    }
  ];

  consumefunction() {
    this.mystring = this.data.values['string4'];
    this.myService.anotherfunc(this.mystring);
  }
}

But I didn't get acces to the object 'string4' with the line:

this.data.values['string4'];

Upvotes: 0

Views: 83

Answers (2)

Adrien Brunelat
Adrien Brunelat

Reputation: 4642

data is an array of objects, if you want to retrieve a property from the object in the array, you need to do the following:

  • this.data will get you the data object you defined as an array, the code encapsulated with [ ].
  • this.data[0] will get you the first object of the array. In your case, there is only one, the piece of code encapsulated with { }.
  • this.data[0].string4 will get you the property you want from this first object.

In short:

this.mystring = this.data[0].string4;

Upvotes: 2

Tianzhen Lin
Tianzhen Lin

Reputation: 2614

There are two issues with the code. One is that data is a local variable in the constructor, not member variable in the class, so it cannot be accessed through this.data. The second issue is that value field is missing in data.

With the following changes you should be able to access it

export class DataComponent {

     mystring: string = '';

     constructor(private myService: myService) {}

     // change this line
     this.data = {
        values: {
          string1: '',
          string2: '',
          string3: '',
          string4: ''
        }
     };

      consumefunction () {

      this.mystring = this.data.values['string4'];

      this.myService.anotherfunc(this.mystring);

      }

}

Upvotes: 0

Related Questions