I recently delved into AngularJS programming and crafted some code. Surprisingly, I'm not encountering any errors - the console displays the desired outcome, but alas, it fails to reflect on the webpage. My aim is to execute 2 HTTP calls: GET and POST. The GET function exhibits all elements from a list while the POST function appends an element to this list. Though both functions seem to operate smoothly, the issue arises when attempting to display all elements; nothing appears :(
Below are snippets of my code:
dataContext.js
(function () {
'use strict';
angular.module('app').service('dataContext', ['httpService', function (httpService) {
var service = {
getAllUsers: getAllUsers,
addUser: addUser,
saveMessage: saveMessage
};
function getAllUsers() {
return httpService.get("api/users");
}
function addUser(name) {
return httpService.post("api/users", { name: name });
}
dashboard.js
(function () {
'use strict';
angular.module('app').controller("dashboardController", ['dataContext', function (dataContext) {
var vm = this;
vm.getUser = function () {
dataContext.getAllUsers().then(
function (response) {
alert(response.data[0].Name);
},
function (error) {
console.log(error);
}
);
};
vm.postUser = function () {
dataContext.addUser(vm.username).then(
function (response) {
alert("User, " + vm.username + " was added!");
},
function (error) {
console.log(error);
}
);
};
})();
httpService.js
(function () {
'use strict';
angular.module('app').service('httpService', ['$http', '$q', 'backendConfig', function ($http, $q, backendConfig) {
var service = {
get: get,
post: post
};
function get(path) {
var deferred = $q.defer();
$http.get(backendConfig.url + path).then(
function (response) {
deferred.resolve(response);
},
function (err, status) {
deferred.reject(err);
}
);
return deferred.promise;
}
function post(path, data) {
var deferred = $q.defer();
$http.post(backendConfig.url + path, data).then(
function (response) {
deferred.resolve(response);
},
function (err, status) {
deferred.reject(err);
}
);
return deferred.promise;
}
return service;
}]);})();
Here is my dashboard.html
<div ng-controller="dashboardController as vm">
<button ng-click="vm.getUser()">Get</button>
<button ng-click="vm.postUser()">Post</button>
<input ng-model="vm.username" />
<ul>
<li ng-repeat="obj in vm.users">{{obj.Name}}</li>
</ul>
The list's name is users, containing a class Users with a string Name. Everything seems aligned correctly, yet unfortunately, the functionality isn't there. Any guidance would be greatly appreciated.
Many thanks!