i tried to retrieve two data, one from the API and from my json, when i make the call i receive just the second call on my view.
json 1
[
{
"id": 1,
"img":"images/clientlogos/21747.jpg"
},
{
"id": 2,
"img": "images/clientlogos/FMI.png"
}
]
jason # from APi call
[
{
"id": 1,
"name": "Enough",
"forecasted": 22,
"budget": 40,
"hoursspent": 3.53999997675419,
"currentcosts": 965.393393660635,
"xerototal": 2800
},
{
"id": 2,
"name": "Fad Ltd",
"forecasted": 96.5,
"budget": 300,
"hoursspent": 199.91000029631,
"currentcosts": 66234.589716303,
"xerototal": 176472
},
]
my factory
app.factory('myFactory', function($http){
return{
client: function(callback){
$http({
method: "GET",
url: "http://www.outleading.co.za/api/api/clientdashboarddata",
cache:true
}).then(callback);
},
list: function(callback){
$http({
method: "GET",
url: "data/Client.json",
cache:true
}).then(callback);
}
};
});
my controller
app.controller('myController', function ($scope, $http, myFactory) {
myFactory.client(function (response) {
var data = response.data;
$scope.myClients = data;
})
myFactory.list(function(response){
var data= response.data;
$scope.myClients= data;
})
};
}
})
my html
inside my ng-repeat i want to get{{client.img}} from my json and {{client.clientname}} from the api call
<div class="card client-card" ng-repeat="client in myClients>
<div class="client-logo">
<img ng-src="{{client.img}}" alt="{{client.name}}">
</div>
</div>
so Any help will be much appreaciated.
You are calling two APIs and overriding the input.
app.controller('myController', function ($scope, $http, myFactory) {
myFactory.client(function (response) {
var data = response.data;
$scope.myClients = data; //Same variable
})
myFactory.list(function(response){
var data= response.data;
$scope.myClients= data; //Same variable
})
};
}
})
Instead of saving data in $scope.myClients in both the calls, use some different variable name. I guess second one should be $scope.lists
Modify factory to return promise it gives you flexibility
app.factory('myFactory', function ($http) {
return {
client: function () {
return $http({
method: "GET",
url: "http://www.outleading.co.za/api/api/clientdashboarddata",
cache: true
});
},
list: function () {
return $http({
method: "GET",
url: "data/Client.json",
cache: true
});
}
};
});
Use $q.all() and wait for all promises to complete
app.controller('myController', function ($scope, $http, myFactory, $q) {
$q.qll(myFactory.client(), myFactory.list()).then(function (result) {
$scope.myClients = result[0].data;
var images = result[1].data;
$scope.myClients.forEach(function(client){
// find index of image for client
var idx= images.findIndex(function(x){
return x.id == client.id
});
client.name = images[idx].name;
})
});
});
Related
I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);
I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}
I have a controller that is calling http.get, http.push and http.post methods.
I am learning angularjs and have found that it's best to call your http.get in your service file. I am able to do that with a simple http.get, but get confused with a http.get by id or http.get/http.post which takes a parameter:
My current controller looks like this
angular.module("app-complaints")
.controller("clcontrol", clcontrol);
function clcontrol($routeParams, $http, $scope) {
$http.get(baseURL + "/api/complaints/" + $scope.complaintCase + "/checklists")
.then(function (cl) {
//success
$scope.index = 0;
$scope.cl = [];
$scope.cl = cl;
}
I want to separate it out like this
controller.js
angular.module("app-complaints")
.controller('clcontrol', function ($http, $scope, $q, Service, $timeout) {
....
getCL();
function getCL(){
Service.getCl()
.success(function(cl){
$scope.cl = [];
$scope.cl = cl;
}
service.js
angular.module("app-complaints")
.factory('Service', ['$http', function ($http) {
Service.getCL = function () {
return $http.get(urlBase + "/api/complaints/" + complaintCase + "/checklists")
};
};
Simple. Make a factory that accepts parameters.
var app = angular.module("MyApp", [ /* dependencies */]);
app.factory("SharedServices", ["$http", function($http) {
return {
getItems: function(url, parameters) {
return $http.get(url, {
//optional query string like {userId: user.id} -> ?userId=value
params: parameters
});
},
postItem: function(url, item) {
var payload = {
item: item
};
return $http.post(url, payload);
},
deleteItem: function(url, item) {
var payload = {
item: item
};
return $http({
url: url,
data: payload,
method: 'DELETE',
});
}
// ETC. ETC. ETC.
// follow this pattern for methods like PUT, POST, anything you need
};
}]);
Use the service in your controller:
app.controller("MainCtrl", ["$scope","SharedServices", function($scope, SharedServices) {
//do things with the shared service
$scope.postMyThings = function() {
SharedServices.postItems('path/to/api', itemsArray).then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
};
$scope.getMyThing = function() {
SharedServices.getItems('path/to/api/get').then(function(response) {
//success callback, do something with response.data
}, function(response) {
//an error has occurred
});
}
}]);
Here is my service:
app.service('trackService', ['$http', function($http) {
var data;
this.topTracks = function(limit) {
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks; console.log(this.data); return this.data;
});
}
}]);
and controller -
app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
$scope.data = trackService.topTracks(10);
//console.log($scope.data);
}]);
how to send data to the controlller using a $http service inside a custom service?
Several problems are $http is asynchronous and your service method topTracks() doesn't return anything. Also you can't return inside success, there is nowhere to return to ... use then() instead
You need to return the promise from service and set the scope in a promise callback in controller
app.service('trackService', ['$http',
function($http) {
var data;
var self = this;
this.topTracks = function(limit) {
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {
api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
format: 'json',
limit: limit
}
}).then(function(result) {
self.data = result.data.tracks;
console.log(self.data);
return self.data;
});
}
}
]);
app.controller('artistSongsCtrl', ['$scope', 'trackService',
function($scope, trackService) {
trackService.topTracks(10).then(function(data) {
$scope.data = data;
//console.log($scope.data);
});
}
]);
Inside your service you are making an asynchronous GET request. In order to let the controller catch that response, you need to return a promise. Here's an example using $q:
app.service('trackService', ['$http', '$q', function($http, $q) {
var data;
this.topTracks = function(limit) {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
}).success(function(result) {
this.data = result.tracks;
console.log(this.data);
d.resolve(this.data);
});
return d.promise;
}
}]);
I use the code below. The content of dataService is all the $http possible in my application. In the controller, I consume this function. The function call a Web Api service, this one is called and return the right response. In the function customerToggleSuccess the data is undefined. I don't understand why.
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
.then(customerToggleData)
.catch(customerToggleError)
}
function customerToggleData(response) {
return response.data;
}
function customerToggleError(response) {
}
}
}());
(function () {
angular.module('myApp')
.controller('customerController', ['$scope', 'dataService', '$http', '$log', CustomerController]);
function CustomerController($scope, dataService, $http, , $log) {
var vm = this;
vm.activeToggle = function (customerId, index) {
dataService.customerToggleActive(customerId, index)
.then(customerToggleSuccess)
.catch(customerToggleCatch)
.finally(customerToggleComplete);
function customerToggleSuccess(data) {
$log.info(data);
}
function customerToggleCatch(errorMsg) {
}
function customerToggleComplete() {
}
}
}
}());
Like this ,
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
}
}
}());
Simply return the $http promise,
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
you can access it by,
dataService.customerToggleActive(customerId, index)
.then(function (response) {
// do your stuff
})
or, you can do,
function dataService($q, $http,) {
var defer = $q.defer();
....
....
$http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
function customerToggleData(response) {
defer.resolve (response.data);
}
function customerToggleError(response) {
defer.reject(response);
}
return defer.promise;
}