尝试创建存储数据并将其传递给不同组件的服务。我的服务如下:
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;
}
我的组件如下所示:
@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 = '';
}
}
}
以下是我的第一个component.html
的样子:
<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>
但是,Angular不喜欢我的服务并抛出异常:
zone.js:260 Uncaught EXCEPTION:./ FirstComponent类出错 FirstComponent - 内联模板:11:54 ORIGINAL EXCEPTION:TypeError: 无法设置未定义的属性'checkIn'
答案 0 :(得分:1)
嗯,错误完美地解释了问题所在:
无法设置属性&#39; checkIn&#39;未定义的
仔细阅读。它表示您正在尝试设置未定义的属性&#39; checkIn&#39 ;.
事实上,您的服务确实
this.selectedDate.checkIn = value;
但您从未定义this.selectedDate
,因此未定义。
您的服务需求
private selectedDate: SelectedDate = {};
(我假设selectedDate应该是私有的,因为你不会导出它的接口,并且调用者可以通过服务的方法访问和更改其状态)