0

I'm trying to convert my directive to use TypeScript This is what I have so far

'use strict';

module app.dashboard {       
    export class Safes implements ng.IDirective {

        static $inject = ['$log', '$http', 'storeFactory'];
        static instance($log, $http, storeFactory) {
            return new Safes($log, $http, storeFactory);
        }
        templateUrl = '/app/shared/mocks/table.html';
        restrict :string = 'A';
        scope: any = {
            title: '=',
            rows: '='
        };                
        link: (scope, element, attrs) => void;

        constructor(private $log, public $http: ng.IHttpProvider) {
            this.link = this._link.bind(this);
        }

        _link(scope, element, attrs) {
            this.storeFactory.getSafes().then(success, failure);

            function success(response) {
                scope.safes = response.data.safes;
                localStorage.setItem('safeCount', scope.safes.length);
                this.$http.get('/app/dashboard/safes/safes.html', { cache: this.$templateCache }).success(function (tplContent) {
                    element.replaceWith(this.$compile(tplContent)(scope));
                });
            }
        }
    }
    angular
        .module('app')
        .directive('safes', Safes.instance);
}

When I get into my success function it says Cannot read property '$http' of undefined

What am I doing incorrectly to not access $http?

1 Answer 1

4

When I get into my success function it says Cannot read property '$http' of undefined

This is because you used function:

function success(response) {

You probably meant to use ()=> (arrow function) which would preserve this context for you.

More : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you for that reference. Another explaination of the issue is in the TypeScript Handbook

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.