2016-06-14 52 views
2

在我的Angular web應用程序中,我有一個名爲ApplicationModule的模塊。 ApplicationModule具有getset的功能。在Angular應用程序中的Javascript鏈接方法

在我的控制器之一,我稱之爲功能象下面這樣:

ApplicationModule.get().then(function (response) { 
    //do something with response 
}); 

GET()函數返回稱爲application的對象。隨着返回的對象,我想用它做些事情。所以我用then來鏈接方法,但我得到一個錯誤,說angular.js:13424 TypeError: Cannot read property 'then' of undefined

更新get()是什麼。

ApplicationModule.get = function() { 
     if (!localStorage.application) { 
      Restangular.all('session').one('user').get().then(function (response) { 
         application = { 
            "id": response.current_application_id, 
            "user_id": response.id, 
            "visa_type": response.current_type 
            } 
       localStorage.setItem("application", JSON.stringify(application)); 
       return application 
      }); 
     } else { 
      return JSON.parse(localStorage.application) 
     } 
} 

我在做什麼錯在這裏?

+0

'。那麼()'通常只用於承諾的語法。你的'.get()'方法不返回一個promise,它返回一個對象。只要做'var response = ApplicationModule.get();' –

+2

顯然'.get()'不會*返回一個對象。如果您希望我們幫助您解決問題,您將不得不向我們展示其代碼。 – Bergi

+0

聽起來像ApplicationModule.get不存在(是未定義的)。你確定它不是GET()?還需要回復一個承諾。 – terpinmd

回答

3

你的方法確實neither return the application也不會在所有返回的對象,如果localStorage.application是falsy。

你正在做的事情的功能是異步的,所以你需要經常返回一個承諾:

ApplicationModule.get = function() { 
    if (!localStorage.application) { 
     return Rectangular.all('session').one('user').get().then(function (response) { 
//  ^^^^^^ returning the promise 
      var application = { 
       "id": response.current_application_id, 
       "user_id": response.id, 
       "visa_type": response.current_type 
      }; 
      localStorage.setItem("application", JSON.stringify(application)); 
      return application; 
//   ^^^^^^ returning the value that the promise will resolve with 
     }); 
    } else { 
     return $q.resolve(JSON.parse(localStorage.application)); 
//    ^^^^^^^^^^ creating a promise here as well for consistent interface 
    } 
} 
+0

返回Restangular是什麼? '$ q.resolve'是做什麼的?從來沒有遇到過這個,所以我希望你能進一步解釋。 – JoHksi

+0

@JoHksi'Restangular'只是Bergi的一個錯字,你應該遵循他在「既不返回應用程序」中提供的鏈接。 ['$ q.resolve'](https://docs.angularjs.org/api/ng/service/$q#resolve)只是向調用函數發送了'ApplicationModule.get()'返回的promise成功完成的信號。 – peteb

+0

@peteb,你是否建議在Restangular前刪除回報呢?我該如何編寫附加功能來捕捉錯誤? 'ApplicationModule.get()'? – JoHksi

0

方法.then()只適用於承諾。爲了對你的應用程序對象做一些事情,我建議把這個值存儲爲一個變量。

var application = ApplicationModule.get(); 
foo(application); 
+0

這不適用於我的應用程序。請查看我上面的評論。 – JoHksi

相關問題