2017-01-24 90 views
2

我有一個angularjs服務在下面定義。在我的角度服務中,我想訪問我的服務變量。有兩個位置:我評論爲「第一本」和「第二本」,在「第一本」中,我可以正確訪問我的「svc」變量,所以this.testvar會給我'foo1'。但是,在「SECOND THIS 「,」this「變量變化,不再是」svc「變量。我怎樣才能在」SECOND THIS「訪問svc變量?訪問服務中的angularjs服務屬性

另外一個側面問題...是否有一個類型的名稱變的是SVC是什麼?它是不是一個JSON,因爲它有一個功能的主要價值之一。

angular 
     .module('myApp') 
     .service('myService', function($q, $http, $cookies, $state) { 
      var svc = { 
      testvar: 'foo1', 
      func1: function(callback) { 

       console.log(this); // FIRST THIS 
       $http.post(endpoint).success(function(response) { 
       console.log(this); // SECOND THIS 
       }).error(function(response, status) { 

       }); 
      }, 
      } 
      return svc 
     } 

回答

1

聲明一個新變量例如, self用於代替this,那麼它在整個服務中意味着相同的事情。

angular.module('myApp').service('myService', function($q, $http, $cookies, $state) { 

    var self = this; // Declare a new variable to act as a handle to "this"; 

    var svc = { 
     testvar: 'foo1', 
     func1: function(callback) { 

      // Use the new variable here. 
      console.log(self); 

      $http.post(endpoint).success(function(response) { 

       // Use the new variable here also. 
       console.log(self); 

      }).error(function(response, status){ 

      }); 
     }, 
    } 
    return svc 
} 

SVC是一個對象

0

在「十二THIS」的範圍(這個)屬於$ HTTP範圍,而不是「 FIRST THIS「。您可以聲明其他變量_that t o保存最後一個範圍,例如:

func1: function(callback) { 

    var _that = this; 

    $http.post(endpoint).success(function(response) { 
    //use _that here :) 
    }).error(function(response, status) { 

    }); 
} 
0

你可以做這樣的事情,希望它helps.Did一些調整。

angular 
    .module('myApp') 
    .service('myService', function($q, $http, $cookies, $state) { 
     var service = this; 
     var testvar = 'foo1'; 

     function func1(callback) { 
     console.log(service); // FIRST THIS 
     return $http 
      .post(endpoint) 
      .success(function(response) { 
      console.log(service); // SECOND THIS 
      }) 
      .error(function(response, status) { 

      }); 
     } 

     function example() { 

     } 

     function exampleOne() { 

     } 

     return { 
     func1: func1, 
     example: example, 
     exampleOne: exampleOne 
     }; 
    };