我正在使用一个名为Lightpick的日期范围插件,并且如果用户选择了开始日期和结束日期。那就是我要在服务上调用方法的时候。
这是我的代码:
Service.ts
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' })
}
public getAttedanceRecord(data): Observable<any> {
return this.http.post(url, data, httpOptions);
}
component.ts
import { JsonFileService } from '../json-file.service';
import * as moment from 'moment-timezone';
import 'moment-duration-format';
import Lightpick from 'lightpick';
export class TimeRecordsComponent implements OnInit {
constructor(public JsonFileService: JsonFileService) {}
ngOnInit() {
var picker = new Lightpick({
field: document.getElementById('datepicker'),
singleDate: false,
footer: true,
selectForward: true,
onSelect: function(start, end){
let startDate = start.format();
let endDate = end.format();
console.log(startDate + " " + endDate);
this.JsonFileService.getAttedanceRecord({
EmployeeId: "00000000-0000-0000-0000-000000000001",
DateFrom: startDate,
DateTo: endDate,
TimeZone: "China Standard Time",
CountryCode: "PHL",
TenantId: "00000000-0000-0000-0000-000000000001",
CompanyId: "00000000-0000-0000-0000-000000000001"
}).subscribe(data => {
console.log(data);
});
}
});
}
}
设置开始日期和结束日期时,总是会引发此错误。
我知道我需要使用其他方法来调用该方法,以便可以使用它。但是我不知道如何。
请帮助我发展。
答案 0 :(得分:2)
您正在使用function()
,它本身是另一个对象。因此,无法通过功能访问服务实例。而是使用允许访问外部成员的粗箭头=>
。
ngOnInit() {
var picker = new Lightpick({
.
.
.
onSelect: (start, end) => {
let startDate = start.format();
let endDate = end.format();
.
.
.
}
答案 1 :(得分:1)
此关键字使用不正确。 问题行是 this.JsonFileService.getAttedanceRecord 。
请尝试以下ngOnInit。
ngOnInit() {
let parent = this;
var picker = new Lightpick({
field: document.getElementById('datepicker'),
singleDate: false,
footer: true,
selectForward: true,
onSelect: function(start, end){
let startDate = start.format();
let endDate = end.format();
console.log(startDate + " " + endDate);
parent.JsonFileService.getAttedanceRecord({
EmployeeId: "00000000-0000-0000-0000-000000000001",
DateFrom: startDate,
DateTo: endDate,
TimeZone: "China Standard Time",
CountryCode: "PHL",
TenantId: "00000000-0000-0000-0000-000000000001",
CompanyId: "00000000-0000-0000-0000-000000000001"
}).subscribe(data => {
console.log(data);
});
}
});
}