SecretIndividual
SecretIndividual

Reputation: 2519

Angular - variable undefined

I am writing a service but am encountering a problem.

The service contains a variable that is implementing an interface. When the service is first created the variable holds the value of undefined.

To explain it with less code I came up with the following example.

This is an interface.

interface objectWithSensors {
  sensor1: number[];
  sensor2: number[];
}

The service has a varaible of this type declared as:

private sensorObject: objectWithSensors;

At this point in time this object is undefined.

Is there a way to define it at this point (put an object in there that I can later modify) or should I change the interface to a class with public attributes?

Upvotes: 1

Views: 1952

Answers (2)

Will Alexander
Will Alexander

Reputation: 3571

You can simply instantiate the object:

private sensorObject: objectWithSensors = {
  sensor1: [],
  sensor2: []
}

Upvotes: 2

ukn
ukn

Reputation: 1793

Use a class if you want to have a default value. Otherwise, do something like that:

sensorObject.sensor1 = [];
sensorObject.sensor2 = [];

Upvotes: 2

Related Questions