【问题标题】:AngularJS - Directive - onClick function calling $http(POST) - $http is undefined?AngularJS - 指令 - onClick 函数调用 $http(POST) - $http 未定义?
【发布时间】:2019-11-15 01:56:48
【问题描述】:

我有一个 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;
    }

}

问题是,点击点击事件时,报错:

未捕获的类型错误:无法读取未定义的属性“帖子”

已生成。

【问题讨论】:

  • 我认为你没有得到 "this" 。使用箭头函数 () => {}
  • 谢谢赛马。发现。就像下面的美里一样。谢谢。

标签: angularjs angularjs-directive angularjs-http


【解决方案1】:

当你写 'function'' 时,'this' 指的是函数本身。 您只需将“功能”替换为() =&gt;{},如下所示:

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));
    }
});  

【讨论】:

    猜你喜欢
    • 2019-11-17
    • 2013-05-28
    • 2015-04-02
    • 2012-11-25
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2020-02-26
    • 2020-11-12
    相关资源
    最近更新 更多