Gabriel Souza
Gabriel Souza

Reputation: 67

Unable to Set Property of Undefined or Null reference

I am trying to set a value to the properties of an Object, but everytime I am getting this error.

I've tried to implement the object inside a class and I also tried to implement and import an interface.

// In my interface I have put:
export interface Despesas {
  totalAlimentacao: string,
  totalHospedagem: string,
}

// And in my Class Service
import { Despesas } from '../interfaces/despesas'

@Injectable({
  providedIn: 'root'
})
export class DespesasService {

  @Input() objectDespesas: Despesas;

  constructor() { }

setDespesas() {
    this.objectDespesas.totalAlimentacao = "2";
  }

// I am calling setDespesas from other place and it is everything fine in the call

Upvotes: 0

Views: 1981

Answers (2)

user11390576
user11390576

Reputation:

It will always be undefined because you have specified the object as an @Input, which comes from a parent template, and services do not have associated templates.

@Input and @Output are for directives/components.

All you have to do is initialise the object in the constructor or in onInit

E.g.

this.objectDespesas = { }

Upvotes: 2

Alejandro Guardiola
Alejandro Guardiola

Reputation: 97

maybe you should try in the constructor of DespesasService to initialize the object

constructor()
{

  this.objectDespesas = {
     totalAlimentacao: '',
     totalHospedagem: ''
  }

}

Upvotes: -1

Related Questions