首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS -指令- onClick函数调用$http(POST) - $http是未定义的?

AngularJS -指令- onClick函数调用$http(POST) - $http是未定义的?
EN

Stack Overflow用户
提问于 2019-07-04 10:30:21
回答 1查看 199关注 0票数 0

我有一个AngularJS指令,它使用$http (ng.IHttpService)调用api中的数据,没有问题。

我将'click‘事件绑定到一个函数中,并希望调用同一个api控制器上的POST请求将一些数据放入数据库中。

这是指令

代码语言:javascript
复制
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”

是生成的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-04 11:54:15

当你写“函数”时,“这”指的是函数本身。您只需将“函数”替换为() =>{},如下所示:

代码语言:javascript
复制
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));
    }
});  
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56886000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档