create service with getter and setting in angular 2? -
trying create service stores data , passes different component. service looks this:
import { injectable } '@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 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 how 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 not service , throw exception :
zone.js:260 uncaught exception: error in ./firstcomponent class firstcomponent - inline template:11:54 original exception: typeerror: cannot set property 'checkin' of undefined
well, error explains problem is:
cannot set property 'checkin' of undefined
read carefully. says you're trying set property 'checkin', of undefined.
and indeed, service does
this.selecteddate.checkin = value;
but have never defined this.selecteddate
, it's undefined.
your service needs
private selecteddate: selecteddate = {};
(i assume selecteddate should private, since don't export interface, , callers can access , change state through methods of service)
Comments
Post a Comment