I created a service using ngResource to save the data of form in json format. But after submitting form I got 404 error for 999.json file.
ServiceJS
"use strict";
eventsApp.factory("eventData", function ($resource, $q) {
var resource = $resource("data/:id.json", {
id: "#id"
});
return {
getEvent: function () {
var deffered = $q.defer();
resource.get({
id: "event"
},
function (event) {
deffered.resolve(event);
},
function (status) {
deffered.reject(status);
});
return deffered.promise;
},
save: function (event) {
var deffered = $q.defer();
event.id = 999;
resource.save(event,
function (data, status, header, config) {
deffered.resolve(data);
},
function (data, status, header, config) {
deffered.reject(data);
}
);
return deffered.promise;
}
}
});
ControllerJS
eventsApp.controller('editEventCtrl', function ($scope, eventData) {
// Save Event
$scope.saveEvent = function (event, newEventForm) {
if (newEventForm.$valid) {
//alert("Event '" + event.ename + "' Saved Successfully !");
eventData.save(event)
.then(
function (response) {
console.log('Success ' + JSON.stringify(response));
},
function (response) {
console.log('Failure ' + JSON.stringify(response));
}
)
}
};
});
Please help me.
Related
I'm new into AngularJS programming and I wrote some code, I don't get any errors, in console it gives me what I want but it dose not show on the web page. I am trying to make 2 HTTP calls, get and post, get shows me all the element I have in a list and post add an element in this list. They are working, but when I try to list all the elements it dose not show me anything :(
Here are 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;
}]);})();
and 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>
List's name is users, I have a class Users with a string Name, everything should be on point but I don't know why it dose not work. Any help will be awesome
Thank you
Replace
alert(response.data[0].Name);
with
vm.users = response.data;
During loading of the partial Html with controller, my function named $scope.actionViewVisitors() is recognized and runs without errors. But whenever I use it inside another function on the same controller, it gives me an error:
TypeError: $scope.actionViewVisitors is not a function. Please see my code below:
angular.module("Visitor.controller", [])
// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
$scope.visitorList = null;
$scope.viewAccountDetail = null;
$scope.avatar = null;
$scope.visitorDetail = null;
$scope.visitorBtn = "Create";
$scope.actionViewAccount = function () {
$scope.actionViewAccount = viewAccountService.serviceViewAccount()
.then(function (response) {
$scope.viewAccountDetail = response.data.account;
$scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
})
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false);
// THIS ONE IS NOT RECOGNIZED
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
// I DON'T GET ANY ERROR HERE
$scope.actionViewVisitors();
$scope.actionViewAccount();
$scope.createVisitor = function () {
$scope.statusMessage = null;
if ($scope.visitorBtn == "Create") {
$scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
.then(function (response) {
if (response.data.response == '1') {
bootbox.alert({
message: "Successfully created a new visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
} else if (response.data.response == '0') {
bootbox.alert({
message: "Failed in creting visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
}
});
debugger;
$scope.visitorDetail = undefined;
// I GET THE ERROR WHEN I CALL THIS METHOD
$scope.actionViewVisitors();
}
}
})
// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
var fac = {};
fac.serviceViewVisitors = function () {
return $http({
url: '/Visitor/ViewVisitors',
method: 'get'
});
}
fac.serviceCreateVisitor = function(visitor) {
return $http({
url: '/Visitor/CreateVisitor',
data: { visitor: visitor },
method: 'post'
});
}
return fac;
}])
You are overwriting the function with Promise in the following line, thus the error is correct
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
Remove $scope.actionViewVisitors =
$scope.actionViewVisitors = function () {
viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
On the first call to the function you are changing it from a function to a Promise. Maybe you want to be returning the result instead?
$scope.actionViewVisitors = function () {
return viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
I wrote one service which takes a data from one controller and send it to another controller. And this controllers are pointing to different modules. Now when I am calling the service function from both the controller it fires some error.
angular.js:13920 ReferenceError: addData is not defined
at Object.dataservice
Here is my service in pages.module.js
(function ()
{
'use strict';
angular
.module('app.pages', [
'app.pages.auth.login',
'app.pages.auth.login-v2',
'app.pages.auth.register',
'app.pages.auth.register-v2',
'app.pages.auth.verify-mobile',
'app.pages.auth.reset-password',
'app.pages.auth.lock',
'app.pages.coming-soon',
'app.pages.error-404',
'app.pages.error-500',
'app.pages.invoice',
'app.pages.maintenance',
'app.pages.profile',
'app.pages.search',
'app.pages.timeline'
])
.config(config)
.factory('dataservice', dataservice);
/** #ngInject */
function config(msNavigationServiceProvider)
{
// Navigation
msNavigationServiceProvider.saveItem('pages', {
title : 'PAGES',
group : true,
weight: 2
});
}
function dataservice(){
var sendarr = [];
this.addData = function(newObj) {
sendarr.push(newObj);
};
this.getData = function(){
return sendarr;
};
return {
addData: addData,
getData: getData
};
}
})();
this is 1st controller login.controller.js
(function ()
{
'use strict';
angular
.module('app.pages.auth.login')
.controller('LoginController', LoginController);
/** #ngInject */
LoginController.$inject = ['dataservice'];
function LoginController(msApi,$state,dataservice)
{
// Data
var vm = this;
vm.login = login;
vm.startApp = startApp;
vm.fbLogin = fbLogin;
var auth2;
// Methods
function fbLogin(){
FB.login(function(response){
if(response.status=='connected'){
testAPI();
}
else if(response.status == 'not_authorized'){
console.log('error');
}
else{
console.log('please log in');
}
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
});
}
function startApp(){
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: '990822731291-21sdd22ujqc78l1q2i2lmf5hfe5satj1.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
fetch_basic_profile: 'true',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('customGoogleBtn'));
});
}
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var pushData = [profile.getId(), profile.getName(), profile.getEmail()];
console.log(pushData);
dataservice.addData(pushData);
$state.go('app.pages_auth_verify-mobile')
},
function(error) {
alert(JSON.stringify(error, undefined, 2));
});
}
function login(){
var jsonData = {"mobile":vm.form.mobile};
msApi.request('login.credentials#save',jsonData,
// SUCCESS
function (response)
{
console.log(response.error);
if(response.error == 1){
vm.form.mobileErrorFlag = true;
}
if(response.error == 0){
vm.form.mobileErrorFlag = false;
}
},
// ERROR
function (response)
{
alert(JSON.stringify(response));
}
)
}
}
})();
This one is the 2nd controller verify-mobile.controller.js
(function ()
{
'use strict';
angular
.module('app.pages.auth.verify-mobile')
.controller('VerifyMobileController', VerifyMobileController);
/** #ngInject */
function VerifyMobileController(dataservice)
{
var data = dataservice.getData();
alert(data);
}
})();
You had the methods as this.addData and this.getData in your dataservice whereas you are accessing the same without this in the return. That's why you are getting this error.
You don't need the this inside the factory service and can remove the same as below.
function dataservice(){
var sendarr = [];
var addData = function(newObj) {
sendarr.push(newObj);
};
var getData = function(){
return sendarr;
};
return {
addData: addData,
getData: getData
};
}
I am trying to make sync calls using a factory pattern.
$scope.doLogin = function (username, password, rememberme) {
appKeyService.makeCall().then(function (data) {
// data = JSON.stringify(data);
debugAlert("login controller app key service"+data);
var appkeyvalue = data.d.appkey;
sessionConfigurationService.setBasicToken(appkeyvalue);
loginService.makeCall(username, password, rememberme).then(function (accessTokenData) {
if (accessTokenData.access_token !== "")
{
sessionConfigurationService.setAccessTokenData(accessTokenData.access_token);
userPreferencesService.makeCall().then(function (userPreferencesData) {
if (userPreferencesData.d.userId !== "")
{
sessionConfigurationService.setUserPreferences(userPreferencesData.d);
// $window.location.href = '/base.html';
}
});
}
});
});
};
My appKeyService factory is
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function () {
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
My authenticated service factory is
app.factory('authenticatedServiceFactory', function ($http, $q, sessionConfigurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function (methodType, URL, data, authType) {
var headerValue = "";
if (authType === "Basic") {
headerValue = sessionConfigurationService.getBasicToken();
} else if (authType === "Bearer") {
headerValue = sessionConfigurationService.getBearerToken();
}
var config = {headers: {
'Authorization': headerValue,
'Accept': 'application/json;odata=verbose',
},
withCredentials: true,
async: false
};
if (methodType === "GET") {
$http.get(URL, data, config)
.then(function (getData) {
debugAlert("GET method response" + JSON.stringify(getData));
deffered.resolve(getData.data);
}, function (error) {
debugAlert("GET method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "POST") {
$http.post(URL, data, config)
.then(function (putData) {
debugAlert("POST method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("POST method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "DELETE") {
$http.delete(URL, data, config)
.then(function (deleteData) {
debugAlert("DELETE method response" + JSON.stringify(deleteData));
deffered.resolve(deleteData.data);
}, function (error) {
debugAlert("DELETE method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "PUT") {
$http.put(URL, config)
.then(function (putData) {
debugAlert("PUT method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("PUT method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
return deffered.promise;
};
return service;
});
But I don't see the service calls are made in sync. So the "then" part in the controller is not executing after we receive the response. Its executing one after the other. How can I make that happen.
#Frane Poljak
Thank you for your comment. I just brought
var deffered = $q.defer();
inside the makeCall method and its working as I wanted now. Thank you!
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var service = {};
service.makeCall = function () {
var deffered = $q.defer();
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
I am leaning Angular my first application is a photo sharing tool. I added the code for the upload function and broke it. I thought I was defining the albumProvider in my controller, but apperently I have failed to do so. The error is Error: [$injector:unpr] Unknown provider. I am stuck and could us a hand on what I need to fix.
albumService.js
(function () {
function albumProvider($http,$fileUploader) {
this.getUploader = function (album_name, scope) {
return $fileUploader.create({
scope: scope,
method: "PUT",
url: "/v1/albums/" + album_name + "/photos.json"
});
};
this.getAlbums = function (callback) {
$http.get("/v1/albums.json")
.success(function (data, status, headers, conf) {
callback(null, data);
})
.error(function (data, status, headers, conf) {
callback(data);
});
};
this.getPhotosForAlbum = function (name, callback) {
$http.get("/v1/albums/" + name + "/photos.json")
.success(function (data, status, headers, conf) {
callback(null, data);
})
.error(function (data, status, headers, conf) {
callback(data);
});
};
this.addAlbum = function (album_data, callback) {
if (!album_data.name) return callback({ code: "missing_name" });
if (!album_data.title) return callback({ code: "missing_title" });
if (!album_data.description) return callback({ code: "missing_description" });
if (!album_data.date) return callback({ code: "missing_date" });
if (!is_valid_date(album_data.date)) return callback({ code: "bad_date" });
$http.put("/v1/albums.json", album_data)
.success(function (data, status, headers, conf) {
callback(null, data);
})
.error(function (data, status, headers, conf) {
callback(data);
});
};
}
photoApp.service("albumProvider", albumProvider);
function is_valid_date(the_date) {
if (the_date.match(/^[0-9]{2,4}[\-\/\. ,][0-9]{1,2}[\-\/\. ,][0-9]{1,2}$/)) {
var d = new Date(the_date);
return !isNaN(d.getTime());
} else {
return false;
}
}
})();
albumUploadController.js
(function () {
function AlbumUploadController($scope, $routeParams, albumProvider) {//Dependency Inject albumProvider
$scope.album_name = $routeParams.album_name;
$scope.page_load_error = '';
$scope.description = {};
albumProvider.getPhotosForAlbum($scope.album_name, function (err, photos) {
if (err) {
if (err.error == "not_found")
$scope.page_load_error = "No such album. Are you calling this right?";
else
$scope.page_load_error = "Unexpected error loading page: " + err.code + " " + err.message;
} else {
$scope.photos = photos;
$scope.uploader = albumProvider.getUploader($scope.album_name, $scope);
$scope.uploader.bind("completeall", function (event, items) {
$scope.done_uploading = true;
});
}
});
$scope.uploader.bind('beforeupload', function (event, item) {
var fn = _fix_filename(item.file.name);
var d = item.file.lastModifiedDate;
var dstr = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
item.formData = [{
filename: fn,
date: dstr,
description: $scope.descriptions[item.file.name]
}];
});
}
photoApp.controller("AlbumUploadController", AlbumUploadController);
function _fix_filename(fn) {
if (!fn || fn.length == 0) return "unknown";
var r = new RegExp("^[a-zA-Z0-9\\-_,]+$");
var out = "";
for (var i = 0; i < fn.length; i++) {
if (r.exec(fn[i]) != null)
out += fn[i];
}
if (!out) out = "unknown_" + (new Date()).getTime();
}
})();
app.js
var photoApp = angular.module('photoSharingApp', ['ngRoute']);
photoApp.config(function ($routeProvider) {
$routeProvider
.when("/albums", {
controller: "AlbumListController",
templateUrl: "/app/partial/albumPartial.html"
})
.when("/album/:album_name", {
controller: "AlbumViewController",
templateUrl: "/app/partial/albumViewPartial.html"
})
.when("/album/:album_name/upload", {
controller: "AlbumUploadController",
templateUrl: "/app/partial/albumUploadPartial.html"
})
.when("/album/photos/:album_name/:photo_filename", {
controller: "PhotoViewController",
templateUrl: "/app/partial/photoViewPartial.html"
})
.when("/", {
redirectTo: "/albums"
})
.when("/404_page", {
controller: "Controller404",
templateUrl: "/app/partial/404Partial.html"
})
.otherwise({
redirectTo: "/404_page"
});
});
you need to set up the file uploader in your app configuration like:
var photoApp = angular.module('photoSharingApp', ['ngRoute','angularFileUpload']);
then as far i know you may change your fileuploader definition for:
return new FileUploader({
scope: scope,
method: "PUT",
url: "/v1/albums/" + album_name + "/photos.json"
});
I'm not sure about passing the scope to the service, but you can try that out, also don't forget to update your dependency from $fileUploader to FileUploader