您好我只想使用一个简单的函数,http post来发布我的日期到一个页面。我希望服务器能够获取我发布的日期。TypeError:无法读取未定义的属性'post'
import { Component, OnInit } from '@angular/core';
import { MarginServcies } from '../../services/MarginService';
import { Response } from '@angular/http';
import { Http} from '@angular/http';
//import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';
@Component({
selector: 'margin',
template: require('./margin.component.html')
})
export class MarginComponent implements OnInit {
public http: Http;
public MarginList = [];
public date: string;
public userdate: string;
pad(i: number) {
return i < 10 ? '0' + i : i;
}
onClick($event: any, userdate) {
userdate = this.date;
//console.log(this.date);
this.http.post('api/date', userdate).subscribe();
}
//get the current date as default
ngOnInit() {
const selectedDate = new Date();
this.date = `${selectedDate.getFullYear()}-${this.pad(selectedDate.getMonth() + 1)}-${this.pad(selectedDate.getDate())}`;
}
public constructor(private marginService: MarginServcies) {
//get Margindata from server
this.marginService.getMargin().subscribe(results => {
this.MarginList = results.json();
//console.log(results.json());
});
}
}
这是我的组件。我正在使用webpack,angular 4.我想在onClick()函数中使用post函数。一旦我点击我可以发布日期。现在我检查console.log()工作正常。错误是:
MarginComponent.html:15 ERROR TypeError: Cannot read property 'post' of undefined
at MarginComponent.onClick (margin.component.ts:25)
at Object.eval [as handleEvent] (MarginComponent.html:15)
at handleEvent (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:22850)
at callWithDebugContext (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:24142)
at Object.debugHandleEvent [as handleEvent] (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:23730)
at dispatchEvent (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:19750)
at vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:20342
at HTMLButtonElement.<anonymous> (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:27870)
at ZoneDelegate.invokeTask (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:83738)
at Object.onInvokeTask (vendor.js?v=8G5nuphpleAMB8hDVj0v8l9es64guglhqGWIwYdey3M:15077)
任何人都可以帮助我吗?谢谢!
我建议你阅读https://angular.io/guide/dependency-injection –
和最佳实践,建议你换你的HTTP调用的服务。如果你愿意,我可以在这里粘贴一些代码。否则我在这里有一个例子:https://github.com/DeborahK/Angular2-GettingStarted – DeborahK