Kero
Kero

Reputation: 1954

create service with getter and setting in angular 2?

Trying to create a service that stores data and passes it to different component. My service looks like this:

import { Injectable } from '@angular/core';

@Injectable()
export class SelectedDateService {
  selectedDate: SelectedDate;
  getCheckIn () {return  this.selectedDate.checkIn; }
  getCheckOut (){return this.selectedDate.checkOut; }
  setCheckIn (value)  {  this.selectedDate.checkIn = value; }
  setCheckOut (value: string) {  this.selectedDate.checkOut = value; }
}
interface SelectedDate {
  checkIn?: string;
  checkOut?: string;
}

My component looks like this:

@Component({
  selector: 'first-component',
  template: require('./first.component.html'),
  styles: [require('./first.component.css')],
  directives: [DatePickerComponent],
  providers: [SelectedDateService]
})
export class FirstComponent {
  constructor(private  dateselectService: SelectedDateService) {
  }  

  onDateChanged(event) {
    if (event.formatted !== '' || event !== undefined ) {
      this.selectedText = event.formatted ;
      this.dateselectService.setCheckIn(this.selectedText);
    }
    else {
      this.selectedText = '';
    }
  }
}

Here is how my first component.html looks like:

<div class="  oa-search-data   nopadding ">
  <date-picker [options]="datePickerOptions"  (dateChanged)="onDateChanged($event)" [dateStyles] = "dateStyle"  [selDate]="date.checkIn" ></date-picker>
    <span class="overlay" [ngStyle]= "{'color': selected}">
      <p> {{pretendedText.start}}
    </p>
  </span>
</div>

However, Angular does not like my service and throw an exception :

zone.js:260 Uncaught EXCEPTION: Error in ./FirstComponent class FirstComponent - inline template:11:54 ORIGINAL EXCEPTION: TypeError: Cannot set property 'checkIn' of undefined

Upvotes: 0

Views: 199

Answers (1)

JB Nizet
JB Nizet

Reputation: 691835

Well, the error perfectly explains what the problem is:

Cannot set property 'checkIn' of undefined

Read it carefully. It says you're trying to set the property 'checkIn', of undefined.

And indeed, your service does

this.selectedDate.checkIn = value;

but you have never defined this.selectedDate, so it's undefined.

Your service needs

private selectedDate: SelectedDate = {};

(I assume selectedDate should be private, since you don't export its interface, and callers can access and change its state through the methods of the service)

Upvotes: 1

Related Questions