我有一个AngularJS指令,可以使用$ http(ng.IHttpService)从api调用数据,而不会出现问题。
我将一个'click'事件绑定到一个函数,并且想在同一api控制器上调用POST请求,以将一些数据放入数据库中。
这是指令
import { Advert } from "../entities";
interface AdvertScope extends ng.IScope {
advert: Advert;
}
export class AdvertDirective implements ng.IDirective {
restrict = 'EA';
templateUrl = '/AngularViews/adverts.html';
scope = {}
constructor(private $http: ng.IHttpService) { }
public link = (scope: AdvertScope, elem: JQuery, attributes: ng.IAttributes, ngModel: ng.INgModelController) => {
this.$http.get<Advert>('/api/adverts/get-adverts')
.then(response => {
scope.advert = response.data;
});
elem.bind('click', function (e: any): void {
var advertId = e.path[0].id;
if (advertId != null && advertId != undefined) {
var data = { advertId: advertId };
// This is just a fire-and-forget post - no success/error handling
this.$http.post('/api/adverts/log-click', JSON.stringify(data));
}
});
}
static factory(): ng.IDirectiveFactory {
var directive = ($http: ng.IHttpService) => new AdvertDirective($http);
directive.$inject = ['$http']
return directive;
}
}
问题是,当点击事件被点击时,错误:
未捕获的TypeError:无法读取未定义的属性“ post”
已生成。
答案 0 :(得分:0)
在编写“功能”时,“此”是指功能本身。
您只需要用() =>{}
替换“ function”,就像这样:
elem.bind('click', (e: any): void=> {
var advertId = e.path[0].id;
if (advertId != null && advertId != undefined) {
var data = { advertId: advertId };
// This is just a fire-and-forget post - no success/error handling
this.$http.post('/api/adverts/log-click', JSON.stringify(data));
}
});