gpt4 book ai didi

angular - 类型错误 : Cannot read property 'post' of undefined

转载 作者:太空狗 更新时间:2023-10-29 18:06:52 24 4
gpt4 key购买 nike

您好,我只想使用一个简单的功能,http 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)

有人可以帮我吗?谢谢!

最佳答案

仅通过声明 public http: Http 不会使 Http 提供程序实例在组件内可用。您必须在构造函数中注入(inject) http 服务,这将带来 http 对象。

public constructor(
private marginService: MarginServcies,
private http: Http //<-- added Http service.
) {
//your code as is
}

Remove the declaration of public http: Http(http declaration) from start of class public http: Http

关于angular - 类型错误 : Cannot read property 'post' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com