2016-09-26 69 views
0

我產生與自耕農 https://github.com/yeoman/generator-angularAngularJS,我的第一個HTML組件「窗口小部件」

我創造了我的第一個航線,目前有什麼在控制器上的指令,什麼寫掙扎的我的第一個AngularJS應用程序,如何指定我從POST或PUT收到的APIService中的JSON消息(我有一個後端準備就緒)..

我創建了一個新服務,並嘗試擴展一個代碼,但出現錯誤:無法讀取屬性'然後'未定義。在服務的代碼是:

angular.module('baApp').service('myService', function ($http, $q) { 

this.getTiers = function(){ 
    $http.get('/data/tiers.json').success(function (data) { 
     console.log('$http tiers'); 
     console.log(data); 
    }); 
}; 
this.getCapabilities = function(){ 
    $http.get('/data/capabilities.json').success(function (data) { 
     console.log('$http capabilities'); 
     console.log(data); 
    }); 
}; 

return this; 
}); 

,這在控制器代碼:

angular.module('baApp') 
    .controller('MyappCtrl', function ($scope, myService) { 

    myService.getTiers().then(function(res){ 
    $scope.tiers = res; 
     console.log('Tiers'); 
     console.log(res); 
    }); 

    myService.getCapabilities().then(function(res){ 
     $scope.capabilities = res; 
     console.log('Capabilities'); 
     console.log(capabilities); 
    }); 

}); 
+0

我編輯我的問題,希望它有助於 – Micky

回答

1

@Micky,

這可能會幫助你jsfiddle

我增加了一些樣品代碼,但如果你需要一些來自api的虛擬數據,直到它準備好了,那麼你可以使用json來模擬api響應。

所以這是示例代碼

var app = angular.module('myApp', []); 
app.controller('ctrl',function($scope, myService){ 
myService.getData().then(function(res){ 
    $scope.data = res; 
}); 
}); 
//service here 
app.service('myService', function($http, $q){ 
var responseJson = {'message':'welcome to angular'} 
this.getData = function(){ 
// call api or json file 
// like 
//return $http.get('api url or /test.json'). 

// fake response here 
var deferred = $q.defer(); 
deferred.resolve(responseJson); 
return deferred.promise; 
} 
return this; 
}); 
+0

賈揚特·你好,感謝您的回答。我應該在哪裏鏈接的HTML文件(模板)?我想使用表或表單作爲模板,並在同一個頁面的HTML中再次使用它們,將它們當作小部件處理。我在考慮並確信您的代碼,yeoman支持將解決:-) – Micky

+0

謝謝@Jayant,但我的json是嵌入式的..存儲在一個外部文件中的變量..我應該做什麼,而不是$ http.get? – Micky