AngularJS service for php files - php

i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!

You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});

Related

angular with mysql to fetch database

I have this working example where i have use $scope and $http in controller to fetch an col from database using get method in variable as given below
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'quizdb.php'
}).then(function successCallback(response) {
// Store response data
$scope.users = response.data;
});
}]);
</script>
now i want this same thing in my factory service i have where i am using hardcoded array. i want to replace the hardcoded array with dynamic array.
with php i am getting an array of but the problem is that i dont know how to implement this thing in factory in angular
my factory is as follows
(function(){
angular
.module("htcssquiz")
.factory("DataService",DataService);
function DataService(){
var dataObj = {
turtleData: turtleData,
quizQuestions: quizQuestions,
correctAnswer : correctAnswer
};
return dataObj;
}
var correctAnswer = [1,2,3,0,2,0,3,2,0,3];
var quizQuestions = [
{
type: "text",
text: "How much can a loggerhead weigh?",
possibilities: [
{
answer: "Up to 20kg"
},
{
answer: "Up to 115kg"
},
{
answer: "Up to 220kg"
},
{
answer: "Up to 500kg"
}
],
selected: null,
correct: null
}
so i want to replace this correctAnswer array with dynamic one.
please help me i am new to angular . thank you in advance.
I am using this factory DataService in The List controller using $inject as follows
(function(){
angular
.module("htcssquiz")
.controller("listctrl", ListController);
ListController.$inject = ['quizMetric','DataService'];
function ListController(quizMetric,DataService){
var vm = this;
vm.quizMetric =quizMetric;
vm.data = DataService.turtleData;
vm.activeTurtle = {};
vm.changeActiveTurtle = changeActiveTurtle;
vm.activateQuiz =activateQuiz;
vm.search = "";
function changeActiveTurtle(index){
vm.activeTurtle = index;
}
function activateQuiz(){
quizMetric.changeState("quiz", true);
}
}
}) ();
This will require a change to both your controller AND your service. The controller will now use the service as if it were the $http call:
fetch.controller('userCtrl', ['$scope', 'DataService', function ($scope, DataService) {
DataService.getCorrectAnswer().then(function (response) {
// Store response data
$scope.correctAnswer = response.data;
});
}]);
Your service will now take responsibility for making the $http call:
DataService.$inject = ['$http'];
function DataService($http){
var dataObj = {
...
getCorrectAnswer : function() {
return $http({
method: 'get',
url: 'quizdb.php'
});
}
};
return dataObj;
}

Attempting to delete contact with Axios inside of Vuejs

I am developing an app to store contact information and utilizing Vuejs and Laravel to do it. I am also using the axios library for CRUD functionality.
I have this error on axios.delete() I cannot figure out. This is my Contacts.Vue file:
<script>
export default {
data: function(){
return {
edit:false,
list:[],
contact:{
id:'',
name:'',
email:'',
phone:''
}
}
},
mounted: function(){
console.log('Contacts Component Loaded...');
this.fetchContactList();
},
methods: {
fetchContactList: function(){
console.log('Fetching contacts...');
axios.get('api/contacts').then((response) => {
console.log(response.data);
this.list = response.data;
}).catch((error) => {
console.log(error);
});
},
createContact: function(){
console.log('Creating contact...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.post('api/contact/store', params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
showContact: function(id){
let self = this;
axios.get('api/contact/' + id)
.then(function(response){
self.contact.id = response.data.id;
self.contact.name = response.data.name;
self.contact.email = response.data.email;
self.contact.phone = response.data.phone;
})
self.edit = true;
},
updateContact: function(id){
console.log('Updating contact '+id+'...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.patch('api/contact/'+id, params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
deleteContact: function(id){
axios.delete('api/contact/'+id)
.then(function(response){
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
}
}
}
</script>
I am getting a TypeError message saying that self.fetchContactList is not a function.
I know that its saying that the value is not actually a function. There is no typo in the function name. Did I call the function on the wrong object? Should I be using a different property name?
I used self.fetchContactList(); on adding and updating contacts, why will it not work with deleting the contact?
Do I need to add request headers? I didn't have to for the other requests.
If I simply remove self.fetchContactList() it will not function at all.
Despite the error, when I refresh the page, it deletes the contact, but I want the contact deleted upon clicking the delete button.
You don't have let self = this; line in deleteContact function, obviously you would get an error.
alternatively, you can use ES6 arrow functions to avoid assigning this to separate variable like this:
deleteContact: function(id) {
axios.delete('api/contact/'+id)
.then((response) => {
this.fetchContactList();
})
.catch((error) => {
console.log(error);
});
}

http_response_code() in php

I'm kind of new to php, I'm using angularJS on the front end that looks like this
app.controller('customersCtrl', function($scope, $http) {
$scope.element = function(num){
var element_id = num;
$http.get("customers.php",{params:{"id":element_id}}).then(function (response) {
$scope.myData = response.data;
});
};
});
PHP code
http_response_code(404);
header("Content-Type: application/json");
exit();
When element_id = 6 I want to fire the http_response_code. Only thing is I'm not seeing anything. The php was taken from the schools example. What am I doing wrong? How do I get the 404 message to display? Am I even thinking of this in the right context? I've some article online but nothing really helps me much. Thanks in advance.
What am I doing wrong?
You are not handling non-success status codes in your $http request.
If you want to get the 404 message then you need to handle the error in your error callback like so:
app.controller('customersCtrl',
function($scope, $http) {
$scope.element = function(num) {
var element_id = num;
$http.get("customers.php", {
params: {
"id": element_id
}
}).then(function(response) {
$scope.myData = response.data;
}, function(error) {
// this is where you handle your error
console.log(error);
});
};
});

Angular ui-router resolve, http success, stateParams

My goal to achieve is:
first to insert new database record with http post, resolve with stateProvider and grab the new id and change view and stateParams.
i have this code for my http post service
myApp.service('postService', ['$http', function($http) {
this.insertNew = function() {
$http.post('create_new.php')
.success(function(data) {
return data;
});
};
create_new.php returns the ID like this (it works, proved with console)
return json_encode($data);
and the stateProvider looks like this (section)
$stateProvider
.state('newRecord', {
resolve: {
newArtID: ['postService',
function(postService) {
return postService.insertNew();
}]
},
params: {
artID: <-- new ID from DB
},
i did tests with stateParams in serval variations (in resolve and by params). how can i bring the new ID to stateParams, so i can access from the views?
Thanks for any help!
I'm not so sure your oder of operations is correct. params is for when you already have that data. You should return the data from your resolve, then you can access it in your scope, for ex:
Service:
.service('postService', function ($http) {
this.insertNew = function () {
return $http.post('create_new.php').then(function (data) {
return data;
});
}
})
Route:
$stateProvider
.state('newRecord', {
views: {
"main": {
controller: 'SomeCtrl',
templateUrl: '...'
}
},
resolvedId: {
newArtID: function (postService) {
return postService.insertNew().then(function (response) {
return response;
});
}
}
})
Controller:
.controller('SomeCtrl', function (resolvedId) {
var newID = resolvedId.id; //depending on what is returned
});

Angularjs How to get Parsed Data of Json Format return by the $http response in Service

First of all i want to clear, That am not accessing the data using web service.
My database(php) and angularjs UI are on the same server it self.
In Service of AngularJs, am sending http Get Request to interface.php(Database) it return json format. I dont how to actually parse the data and send it to Controller ?
Here Clear Cut Code :)
var app=angular.module("app.chart.ctrls",['ngSanitize']);
Controller
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data= registerService.getYears();
**how to parse the data is it correct format or not ? in Controller**
}
**Service**
app.factory('registerService', function ($http,$q,$log) {
return {
getYears:function () {
var deferred = $q.defer();
$http({
method : "GET",
url : "interface.php",
}).success(function(data){
**** How to Return the data from here to Controller ***
})
},
}
});
interface.php
1 - First define a object in your controller that later you can use as a storage for your http response like this :
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data = {};
// fire your servise function like this :
registerService.getYears($scope);
}
2- In your Servise :
app.factory('registerService', function ($http) {
return {
getYears:function (scope) {// scopes comes from your controller
$http({method : "GET",url : "interface.php"})
.success(function(data){
scope.data = data;!!!!!!
})
}
}
});
It's done so far and it'll work ;
BUT if your want to use some kind of promise , you can do like this :
in your controller :
.
.
.
$scope.data = {};
// fire your servise function like this :
var promise = registerService.getYears();
promise.then(function(msg){
$scope.data = msg.data[0];
});
.
.
.
in your Service :
app.factory('registerService', function ($http) {
return {
getYears:function () {
var promise = $http({method : "GET",url : "interface.php"});
}
return promise ;
});
from https://docs.angularjs.org/tutorial/step_11
the source:
[
{
"age": 13,
"id": "motorola-defy-with-motoblur",
"name": "Motorola DEFY\u2122 with MOTOBLUR\u2122",
"snippet": "Are you ready for everything life throws your way?"
...
},
...
]
your service looks like:
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
and your controller:
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone', function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
so, you call the service from within the controller and get the results back.

Categories