How to get the http request data in my example? - javascript

I am trying to get the http request result in my first controller. The http request is triggered by another controller. The problem I have is I am not sure how to detect if the request is done in my first controller. I have something like
First controller:
//I am not sure how to get the customer result if
//http requests are trigger by another controllers here.
customerFactory.getCustomerResult????
Second controller:
//trigger the http request..
var id = 1;
$scope.clickme = function() {
var obj = customerFactory.callApi(id)
}
My factory
customerFactory.callApi = function(id) {
return getCustomer(id)
.then(function(customer) {
return customer;
})
}
var getCustomer = function(id) {
return $http.get('/api/project1/getCustomer' + id);
}
return customerFactory;
html
<div ng-controller="firstCtrl">
//codes...
</div>
//other codes..
//other codes..
<div ng-controller="secondCtrl">
//codes...
</div>
The first and second controller are not related. They are far away from each other. How do I let firstCtrl detect the http request is done and get the customer data? Thanks a lot!

You can use a factory or a service which is a singleton to both be responsible for making the request and storing the data. The service and factory are both singletons and so the single instance persists for the execution of the application and the data and functions can be referenced from the controllers by injecting the factory or service (both are ways of defining providers with more concise syntax when configuration before use of the service/factory via a provider isn't needed).
angular.module("exampleApp", []).service('ExampleService', ["$http", "$q" ,function ($http, $q) {
var service = {
returnedData: [],
dataLoaded:{},
getData = function(forceRefresh)
{
var deferred = $q.defer();
if(!service.dataLoaded.genericData || forceRefresh)
{
$http.get("php/getSomeData.php").success(function(data){
angular.copy(data, service.returnedData)
service.dataLoaded.genericData = true;
deferred.resolve(service.returnedData);
});
}
else
{
deferred.resolve(service.returnedData);
}
return deferred.promise;
},
addSomeData:function(someDataToAdd)
{
$http.post("php/addSomeData.php", someDataToAdd).success(function(data){
service.getData(true);
});
}
};
return service;
}]).controller("ExampleCtrl", ["$scope", "ExampleService", function($scope, ExampleService){
$scope.ExampleService = ExampleService;
}]).controller("ExampleCtrl2", ["$scope", "ExampleService", function($scope, ExampleService){
ExampleService.getData();
$scope.ExampleService = ExampleService;
}]);

Related

call AngularJs first controller method from second controller

I have two AngularJs Controllers called "HomeController" and "VacancyController".
My HomeController have method getallData(). Below I am trying to call Homecontroller's getallData() function through ng-change event of the dropdown.
Please advise how do I call getallData() functiona as my dropdown on-change attribute is wrapped around "VacancyController"?
Below is my code:
HTML
<div ng-controller="VacancyController">
<p>Select a Vacancy:</p>
<select ng-model="selectedVacancy" ng-options="x.name for x in vacancieslist" ng-change=""></select>
<h1>Your selected Vacancy Title is : {{selectedVacancy.name}}</h1>
HomeController
.controller('HomeController', function ($scope, angularSlideOutPanel, $http, $location, $window) {
getallData();
//******=========Get All Teachers=========******
function getallData() {
$http({
method: 'GET',
url: '/Home/GetAllData'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!';
console.log($scope.message);
});
};
VacancyController
app.controller('VacancyController', ['$scope', 'VacancyService', function ($scope, VacancyService) {
$scope.GetVacancies = function () {
$scope.vacancieslist = [];
var getData = VacancyService.Vacancies();
getData.then(function (ord) {
angular.forEach(ord.data, function (val) {
if ($.trim(val).length > 0) {
var obj = new Object();
obj.name = val.VacTitle;
obj.id = val.VacNo;
if (val.VacNo > 0) {
$scope.vacancieslist.push(obj);
}
}
});
}, function () {
genericService.warningNotify("Error in getting List of Vacancies");
});
}
$scope.GetVacancies();
}]);
It is possible for one controller to call another controller, as shown in the following stack overflow(Can one controller call another?). You can use emit or broadcast depending on whether they are a child of another.
However in your case, it is better for getAllData to be placed in a service. The service would return the result of getAllData. In the service you can then either always return the result of getAllData from a http call, or cache the service (by setting it to a variable and returning it)
app.service('commonSvc', function() {
var getAllData = function{... //what you have in your code}
return {
getAllData:getAllData
}
}
By having this commonSvc, you can inject and invoke this service each time you need to call this function, similar to what you are doing for VacancyService. Keep in mind, all service in Angular are singletons. In vacancyController you can then introduce a new function onChange which calls commonSvc.getAllData.

how to start angular service (post, get and delete)

I generate a code with editor.swagger and I want to code a GUI with angular for that code. Since I'm newbie in angular, I dind't understand well how to start programming. I first decide to create 3 files : index.html, index.js and service.js.
Here is a part of my code :
I don't know if it's the good beginning or not. But the problem is that I don't have any idea how what I should do for POST and DELETE. Can you help me please?
You can do the standard 4 methods in Angluar JS(POST,GET,PUT,DELETE). To use these in angular you have to use the $http service that angular provides. To find out more about it check their documentation: https://docs.angularjs.org/api/ng/service/$http
From the Angular $http documentation:
Complete list of shortcut methods:
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
$http.patch
You can also use the method parameter in the $http service. So $http(method: 'DELETE', ...)
var app = angular.module('app');
app.service('apiService', ['$http', function($http){
this.get = function(){
return $http.get(URL);
};
this.delete = function(id){
return $http.delete(URL, id);
}
this.post = function(data){
return $http.post(URL, data);
}
}]);
app.controller('controller', ['$scope', 'apiService', function($scope, apiService){
var getData = apiService.get().success(function(){
});
}]);
You can use $resource and return it as a service.
app.factory('factoryResource', ['$resource', function($resource) {
var resource = {
getResource: function(context) {
var rsc = $resource(context, {}, {'update': {method: 'PUT'}});
return rsc;
}
};
return resource; }])
In your controller you should inject the newly created service as below:
app.controller('myCtrl', function($scope, factoryResource) {
$scope.resource = factoryResource.getResource('http://localhost:8080/api/v1/projects');
$scope.resource.save(object, successCallback, errorCallback); //post
$scope.resource.query(successCallback, errorCallback); //get all
$scope.resource.get({id: object.id}, successCallback, errorCallback); //get a specific object
$scope.resource.delete({id: object.id}, successCallback, errorCallback); //delete
}
Hope this helps;
Basically we have 4 method for a REST operation
Create (POST)-- To Create a new User (just for an example, it can be anything)
Read (GET) -- To get all users
Update (PUT) -- To update a user's property
Delete (DELETE) -- To delete a user
Let me know if you need further clarification.
In angular using service you can do that.
var app = angular.module('app', []);
app.factory('UserService', function($http){
var user = {};
user.post = function(data){
return $http.post('url', data);
}
user.get = function(){
return $http.get('url');
}
user.delete = function(id){
return $http.delete('url');
}
user.update = function(id, data){
return $http.put('url', data);
}
return user
});
app.controller('Controller', function('UserService'){
// Get
UserService.get().success(function(){
});
UserService.post(data).success(function(){
});
UserService.delete(id).success(function(){
});
UserService.get(id, data).success(function(){
});
})
This can be done easily through $resource, if you URL is proper rest.

Set Angularjs Service data to Controller Variable

I am trying to set the controllers scope variable to the data, however no luck. The console.log in the controller shows undefined. Appreciate the help!
My angular service has the following code --
service('VyrtEventService', ['$http', function($http) {
var events = [];
this.getArtistEvents = function(artistId) {
var url = '/api/users/' + artistId + '/';
var promise = $http.get(url).success(function(data, status, headers, config) {
events = data.artist.events;
console.log(events);
return events;
}).catch(function(error) {
status = 'Unable to load artist data: ' + error.message;
console.log(status);
});
return promise;
};
}]);
And I am referencing it in the controller as follows --
VyrtEventService.getArtistEvents($scope.artistId).then(function(data){
$scope.events = data.data.artist.events;
});
console.log($scope.events);
You should just set $scope.events = data in your controller cause your promise already returns data.artist.events when it resolves
To pass scope to service from anywhere in controller. Make sure you inject service .
controllersModule.controller('MyCtrl', function($scope, $filter, $http, $compile, ngTableParams, **FactoryYouwant**)
{
**FactoryYouwant**.getdata($scope.**scopeYoutwantTopass**).then (function(responseData){
var ResponseFromServer =responseData.data;
}
in service
controllersModule.factory('**FactoryYouwant**, function($http) {
var responseData = null;
return {
getdata : function(**data**){ (you dont have to use $)
responseData = $http.post or whatever actually gets you data;
return responseData;
}
};
});
I hope this helps you to call get data from service anywhere in controller.

Not able to get the WCF Result in Angular JS with HTML5

I want bind the values from WCF service to controller. but am not able to bind the values from WCF result. but if i use online webservice means its working perfectly.
please help me. i wasted lots of time. i share the code and screen which is worked.
This is My HTML Code.
<div ng-controller = "fessCntrl">
<ul><li ng-click="alertSwap()">click </li></ul>
<ul><pre>data {{data|json}}</pre></ul>
</div>
This is my Angular JS Code
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function ($scope, stockData) {
$scope.alertSwap = function () {
stockData.query('somedata')
.then(function (result) {
$scope.data = result.data;
}, function (result) {
alert("Error: No data returned");
});
}
});
fessmodule.$inject = ['$scope', 'Data'];
fessmodule.factory('stockData', ['$http', '$q', function ($http, $q) {
var factory = {
query: function (value) {
// here you can play with 'value'
var data = $http.get('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json');
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
This is perfectly working Online webservice.
This my webservice which is not working my WCF Service.
try this
query: function (value) {
// here you can play with 'value'
var data =[];
**$http.get('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json').success(response)
{
data = response;//Or value=response.Data;
};**
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
Instead of your's ..

AngularJS 1.2 cross origin requests are only supported for HTTP

Is there any way to configure Angular app to make it available?
Im using a factory.
By the way, I'm using localhost as webserver but I'm making a request to other server (same network).
angular.module('demoApp.factories', [])
.factory('dataFactory', ['$http', function($http) {
var urlBase = 'external-server:8080';
var dataFactory = {};
dataFactory.getTest = function () {
return $http.get(urlBase + '/test');
};
return dataFactory;
}]);
Finally found the solution. Will post here, maybe it can help others:
angular.module('demoApp.factories', [])
.factory('dataFactory', ['$http', function($http) {
var urlBase = 'external-server:8080';
var dataFactory = {};
dataFactory.getTest = function () {
//Note the $http method changed and a new parameter is added (callback)
//the value of the callback parameter can be anything
return $http.jsonp(urlBase + '/test?callback=myCallback');
};
return dataFactory;
}]);
The controller file basically just calling this factory:
angular.module('demoApp.controllers', []).controller('controller1', ['$scope', 'dataFactory',
function ($scope, dataFactory) {
$scope.status;
$scope.data;
dataFactory.getTest().success(function (data)
{
$scope.data = data;
}).error(function (error)
{
$scope.status = 'Unable to load customer data: ' + error.message;
});
You may be looking to configure the $httpProvider as specified here: http://better-inter.net/enabling-cors-in-angular-js/
Another way is to create a simple http proxy on your front-end server to make external requests look like to angular that they're coming from the same server.

Categories