angularjsangularjs-directiveangularjs-http

AngularJS - Directive - onClick function calling $http(POST) - $http is undefined?


I have an AngularJS directive that calls data from an api using $http (ng.IHttpService) with no problems.

I have the 'click' event bound to a function and want to call a POST request on the same api controller to put some data in a database.

Here is the directive

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

}

Problem is, when the click event is hit, the error:

Uncaught TypeError: Cannot read property 'post' of undefined

is generated.


Solution

  • When you write 'function'', so 'this' refers to the function itself. You just have to replace "function" with () =>{} like this:

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