Trying to utilize the Angular promise API in my application has left me feeling a bit puzzled. I set up a factory as shown in the code snippet below:
factory('transport', function ($resource) {
var baseUrl = "http://aw353/WebServer/odata/Payments";
return $resource("", {},
{
'getAll': { method: "GET",params: {svcUrl:"@svcUrl"}, url: baseUrl + ":svcUrl" },
'save': { method: "POST", params: {svcUrl:"@svcUrl"}, url: baseUrl+ "(:svcUrl)" },
'update': { method: 'PUT', params: {svcUrl:"@svcUrl", key: "@key" }, url: baseUrl+ "(:svcUrl)" + "(:key)"},
'query': { method: 'GET', params: {svcUrl:"@svcUrl", key: "@key" }, url: baseUrl +"(:svcUrl)" + "(:key)"},
'remove': { method: 'DELETE', params: {svcUrl:"@svcUrl", key: "@key" }, url: baseUrl + "(:svcUrl)" + "(:key)"}
});
});
When incorporating this factory in a controller and defining the function as follows:
var getData = function () {
(transport()).$getAll({svcUrl:"//BasicSettings"})
.then(function (data) {
$scope.DataSource = data.value[0];
console.log($scope.DataSource.SystemName);
});
}();
it encounters an error stating "Cannot read property '$getAll' of undefined". However, using the 'new' keyword like this
var getData = function () {
(new transport()).$getAll({svcUrl:"//BasicSettings"})
.then(function (data) {
$scope.DataSource = data.value[0];
console.log($scope.DataSource.SystemName);
});
}();
solves the issue.
I comprehend the distinction between a constructor function and a regular function. Yet, I am puzzled as to why the promise API only functions in the latter scenario.
Could someone provide insight into the working mechanism behind this?