$scope is undefined outside of $http.get() - javascript

My angular code:
angular.module('MyApp',[]).
controller('ProductController', function ($scope, $http) {
$scope.Product = {};
$scope.categoryList = null;
$scope.LoadCategory = function () {
$scope.a = 'sss';
$http.get('/Product/GetAllCategory/')
.success(function (data) {
if (data.success == true)
{
console.log = (data.data);
$scope.categoryList = data.data;
}
else {
alert('aws');
}
})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ": " + textStatus + ": " + errorThrown, 'Error!!!');
})
};
});
and I fetched data using $http.get() from this server side code
public JsonResult GetAllCategory()
{
//List<tblCategory> categories = new List<tblCategory>();
try
{
using (CurtainHomesDBEntities dc = new CurtainHomesDBEntities())
{
var categories = dc.tblCategory.Select(a => new { a.Id, a.CatagoryName }).ToList();
return Json(new { data = categories, success = true }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(ex);
}
}
I debugged using firebug. It fetched data from server side and inserted to $scope.categoryList. But after coming the debug outside of if(data.success==true), $scope.categoryList is undefined.
What is the problem here? I could not find out.

$http.get('/Product/GetAllCategory/') returns an HttpPromise.
I would use the following (from angularjs documentation here)
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Related

Making Sync calls using promises Angular JS factories

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;
});

angular $http.get() not sending signal to server after $http.post

I started using angular a week ago and I have been banging me head trying to solve this problem. I have a service that wraps $http because multiple controllers call the same url. There is one page that has a lot of business logic on the server on a post so I want to call $route.reload(). It seems to work because after vm.saveItem() the controller is reinitialized, but the $http.get() never sends the signal to the server for the new data. What am I doing wrong?
myModule.factory("itemRepository", function ($http) {
var baseUrl = "/api/inventory";
return {
getLocations: function (itemName) {
return $http({
url: baseUrl + "/" + itemName + "/locators",
method: "GET",
cache: false
});
},
addNewLocator: function (itemName, newLocator) {
return $http.post(baseUrl + "/" + itemName + "/locators", newLocator);
}
};
});
// itemEditorController.js
(function () {
"use strict";
angular.module("app-inventoryitems")
.controller("itemEditorController", itemEditorController);
function itemEditorController($routeParams, $route, itemRepository) {
// initialize vars
var vm = this;
vm.itemName = $routeParams.itemName;
vm.errorMessage = "";
// Models
vm.items = [];
vm.isBusy = true;
vm.newLocator = {};
vm.newLocator.name = vm.itemName;
// PROBLEM HERE, does not call server after post new data
// and $route.reload() was called
itemRepository
.getLocations(vm.itemName)
.then(function (response) {
angular.copy(response.data, vm.items);
}, function (err) {
vm.errorMessage = "Failed to load batches.";
})
.finally(function () {
vm.isBusy = false;
});
vm.saveItem = function () {
vm.isBusy = true;
itemRepository.addNewLocator(vm.itemName, vm.newLocator)
.then(function (response) {
vm.newLocator = {};
$route.reload();
}, function (error) {
vm.errorMessage = "Failed to save new item.";
})
.finally(function () {
vm.isBusy = false;
})
}
}
})();
Try to add dynamic parameter to your request:
$http({
url: baseUrl + "/" + itemName + "/locators",
method: "GET",
cache: false,
params: {
r: Math.random().toString(16).substr(2)
}
});
If issue was solved, need looking for HTTP Caching policies.
Google for necessary server-side headers.

Factory return returning function, not product of function

I have implemented a promise inside the factory which seems to work. However I seem to be returning the function ... not the product of the function. If I console log I am seeing the full function printed out in the console instead of the data.
Have I messed up the way the data is return?
Object {data: function} <-- from console log
latestScores.factory('importIO', function($q) {
return {
data: function(){
var deferred = $q.defer()
setTimeout(function() {
var io2 = new importio("xxx", "xxx", "import.io");
io2.connect(function(connected) {
if (!connected) {
console.error("Unable to connect");
return;
}
var data;
var callback = function(finished, message) {
if (message.type == "DISCONNECT") {
console.error("The query was cancelled as the client was disconnected");
deferred.reject(new Error('No name specified for greeting'))
}
if (message.type == "MESSAGE") {
if (message.data.hasOwnProperty("errorType")) {
console.error("Got an error!", message.data);
} else {
data = message.data.results;
deferred.resolve(data)
}
}
if (finished) {
data = message.data.results;
deferred.resolve(data)
}
};
io2.query({
"connectorGuids": [
"xxx"
],
}, callback);
});
}, delay)
return deferred.promise
}
}
});
latestScores.controller('ScoresController', function($scope, importIO) {
$scope.liveScores = importIO.data;
console.log($scope.liveScores); /* returns a console log of function not data */
});
Thanks for your time.
You are assigning the function to $scope.liveScores not the result.
You make use of promises like this:
importIO.data().then(function(result){
$scope.liveScores = result;
console.log($scope.liveScores);
});
This means you execute data function and then, after the method "data" is complete, you assign the result to liveScores.
Since importIO.data() is a function..try this:
latestScores.controller('ScoresController', function($scope, importIO) {
importIO.data().then(function (result) {
$scope.liveScores = result;
console.log($scope.liveScores);
});

Getting 404 not found while creating new json file by Angular $resource

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.

Promises in angularjs controller - how to implement

I am trying to implement a basic function using promises in one of my controllers just so I can ensure it is working correctly before adding in more complex functionality. I am getting a "TypeError: undefined is not a function" on the ".then(function(data){" in the lockPromise method.
Function called from view
$scope.lockPromise = function(fieldId) {
$scope.getLockMessage2(fieldId).getWeather()
.then(function(data) {
if (data === "returned SUCCESS info") {
alert("data is good");
} else {
alert("FAILED");
}
}, function(error) {
alert(error);
});
};
Second function in ctrl
$scope.getLockMessage2 = function(fieldId) {
return{
getWeather: function() {
return $http.get('/api/getData')
.then(function(response) {
if (typeof response.data === "string") {
return response.data;
} else {
return $q.reject(response.data);
}
}, function(response) {
return $q.reject(response.data);
});
}
};
};
API GET
[Route("api/getData")]
public HttpResponseMessage GetData()
{
string data = JsonConvert.SerializeObject("returned SUCCESS info");
return new HttpResponseMessage
{
Content = new StringContent(data, Encoding.UTF8, "application/json")
};
}
EDIT 1:
code updated to reflect comments
Change
$scope.getLockMessage2(fieldId).then
to
$scope.getLockMessage2(fieldId).getWeather().then
Your $scope.getLockMessage2 return an object, not function.
I think the code should be (not tested):
$scope.lockPromise = function(fieldId) {
$scope.getLockMessage2(fieldId).getWeather()
.then(function(data) {
if (data === "good") {
alert("data is good");
} else {
alert("FAILED");
}
}, function(error) {
alert(error);
});
};

Categories