I encountered a challenge while working with AngularJS & REST. My data service was not returning data in time for my model to use, despite implementing a promise.
I would greatly appreciate any assistance from those more knowledgeable on this matter.
In my routing, a booking Id is passed to the bookingController. This controller retrieves booking details and displays them in an editable form in the booking.html template.
testLabApp.controller('bookingController', function ($q, $scope, $location, $window, $routeParams, service) {
if ($routeParams.id) {
$scope.bId = $routeParams.id;
// I set up a promise here
var bookdefer = $q.defer();
bookdefer.promise
.then(function (booking) {
$scope.booking = booking;
$scope.editableBooking = angular.copy($scope.booking);
console.log("[bookingCtrl] 1 New: " + $scope.booking.Storeno + " and Editable: " + $scope.editableBooking.Storeno);
});
bookdefer.resolve(service.getBooking($scope.bookingId));
}
else {
//...
}
When the code reaches '[bookingCtrl] 1...', it throws an error "TypeError: Unable to get property 'Storeno' of undefined or null reference," indicating that the booking data may not have been retrieved yet.
The console then shows:
[getBooking] Done = Id: 209 | Store no: 9180 | Description: test | Status: Booked
My data service consists of functions that make REST calls:
testLabApp.factory('service', ['$rootScope', '$http', function ($rootScope, $http) {
var service = {};
$http({
method: 'GET',
url: "/_api/web/lists/GetByTitle('Bookings')/Items?$filter=Id eq '" + bookingId + "'",
headers: {
'Accept': 'application/json; odata=verbose'
},
}).success(function (d) {
var e = d.d.results[0];
booking = {
Id: e['Id'],
Storeno: e['Title'],
BookedBy: e['BookedBy'],
Description: e['Description'],
StartDate: e['StartDate'],
EndDate: e['EndDate'],
Status: e['Status']
};
console.log("[getBooking] Done = Id: " + booking.Id + " | Store no: " + booking.Storeno + " | Description: " + booking.Description + " | Status: " + booking.Status);
return booking;
}).error(function (er) {
console.log("[getBooking] http error : " + er);
});
};
Any guidance or suggestions would be highly appreciated.
Regards, Craig