0

Here is my TypeScript/AngularJS controller:

class Some {

    static $inject = ["$scope", "bookmarkService", "crawlerService"];

    public allBookmarks;

    constructor(protected $scope, 
                protected bookmarkService, 
                protected crawlerService) 
    {
        $scope.allBookmarks = "+++";
        this.$scope.allBookmarks = "***";
        this.allBookmarks = "---";
        this.getBookmarks();
    }

    public getBookmarks(): void
    {
        this.bookmarkService.getBookmarks()
                .then(function(data) {
                    this.allBookmarks = data;
                    this.$scope.allBookmarks = data;
                }, function() {
                    return "error";
                });
    }

First of all I get the error:

TypeError: Cannot set property 'allBookmarks' of undefined

I tried to debug this code and I see that the value I set in the constrictor is 'undefined' in the getBookmark() method. I think the reason of the error: this is the Object in constructor, but this is Window in the getBookmark() method.

How can I fix code?

PSL
  • 123,204
  • 21
  • 253
  • 243
ceth
  • 44,198
  • 62
  • 180
  • 289
  • You could use [arrow operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), i.e `.then(data => { this.allBookmarks = data... ` TS polyfills it in ES5 mode. – PSL Sep 02 '15 at 18:47
  • does `this.$scope` is defined? definitely `this.$scope.allBookmarks` will throw an error – Pankaj Parkar Sep 02 '15 at 18:48

0 Answers0