how to post data from angular service to laravel controller - angularjs

this is my angular controller which i use it in laravel but when i submit my form i get
MethodNotAllowedHttpException
app.service('post_service', function ($http) {
create = $http.POST('/post', JSON.stringify(data)).then(
function mySuccess(response) {
debugger
$scope.myWelcome = response.data;
},
function myError(response) {
debugger
$scope.myWelcome = response.statusText;
}
)
});
app.controller('postController', ['$scope', function ($scope, post_service) {
$scope.message = 'AddPosts';
// $scope.post=null;
$scope.save = function (data) {
post_service.create(data)
}
}]);
my route config is this :
Route::resource('post', 'PostController');
like you see i using resource controller which allow us to use all type of routing like store index or....
for more detail: my form is simple angular form which contains no token string like csrfToken or some thing like that

You can use the this Route::post('/postData', 'PostController#action');
in the angular service
$http.POST('/postData', JSON.stringify(data)).then(
code here
);

Related

How to pass $http data from Service to Controller in AngularJS

AngularJS not working when I pass controller to the view
I have a problem and I can't troubleshoot it. In my simple app (very simple) I have a service that provides of users info. In angular I have an mvc which is trying to bind the info into the view.
The problem: when I pass the controller to the view, in the route directive, angular stops working in the view. I'm using a simple test {{1+1}} to verify if angular is working.
controller:
App.controller("loginController", function ($scope, usersModel) {
$scope.users = usersModel.getUsers();
})
model
App.service("usersModel", function () {
this.getUsers = function ($scope) {
$http.get("http://localhost:50765/api/users");
}});
The service should inject the $http service and return the promise that it returns
App.service("usersModel", function ($http) {
this.getUsers = function () {
return $http.get("http://localhost:50765/api/users");
}
});
And extract the data from the promise:
App.controller("loginController", function ($scope, usersModel) {
var promise = usersModel.getUsers();
promise.then(function(response) {
$scope.users = response.data;
});
})

How to pass response data from server to $scope in Angular

I have controller in my project, the controller has a method that takes data from login input and sends it on server. Also I have an $http service with .then promise which returns me User's data from database. Everything is working correctly,but I can not pass response data to $scope. For example I want to greet authorized user like "Welcome,Username", but response data is not passing to $scope in template. Here`s my code:
auth.controller.js:
(function() {
"use strict";
angular
.module("MainModule")
.controller("AuthCtrl", function ($scope, $http) {
$scope.login = function () {
var loginData = {
email: $scope.log_email,
password: $scope.log_password
};
console.log(loginData);
$http.post('/login', loginData)
.then(function onSuccess(response) {
console.log(response.data.first_name);
$scope.first_name = response.data.first_name;
});
};
});
})();
And template file:
header.html:
<div ng-controller="AuthCtrl">
<h3>Wellcome</h3> <span>{{first_name}}</span>
</div>
Can anybody tell me what I'm doing wrong? Thanks.

How broadcast data of HTTP post method in angularjs

I'm using the same HTTP method in different controller like following sample:
Service:
var method="sampleMethod"
HotalStatisticService.GetReservations = function (data) {
return $http({
method: 'POST',
data: data,
cache: false,
url:'http://sample.com/'+method
});
}
first controller
.controller("SampleACtrl", function ($scope,HotalStatisticService ) {
HotalStatisticService.GetReservations({start:start, end:end, type:type})
.success(function (data) {
$scope.sampleA=data;
})
}
second controller
.controller("SampleBCtrl", function ($scope,HotalStatisticService ) {
HotalStatisticService.GetReservations({start:start, end:end, type:type})
.success(function (data) {
$scope.sampleB=data;
})
}
How do I use here method in the only one controller?
Let me say that the other solution that uses factories is probably a MUCH better solution.Using Services is also a good option.
Another ,perhaps crude way to do it is using $rootScope.Answer below.
What you essentially want to do is share data between the two controllers. Based on your reply from the comments, both the controllers belong to the same module.You can use $rootScope here to act as a common point.
As you can see, i've added $rootScope as a dependency in both the controllers and simply printed the txt variable in the second div.
JS Code
var app = angular.module('plunker', []);
app.controller('ACtrl', function($scope,$rootScope) {
$scope.name = 'This is Controller A ';
$scope.execute = function() {
alert('Executed!');
}
$rootScope.txt="Hi there from the other side";
});
app.controller('BCtrl', function($scope,$rootScope) {
$scope.name = 'This is Controller B ';
});
HTML
<div ng-controller="ACtrl">
<p>Hello {{name}}!</p>
</div>
<div ng-controller="BCtrl">
<p>Hello {{name}}!</p>
{{txt}}
</div>
Here is the DEMO
What I'd do is create a factory service that handles your HTTP requests, and then inject that service into your controllers... Code would look something like this:
var app = angular.module('sampleApp');
app.factory('sampleFactory', ['$http',
function($http) {
return {
getData: function(success, fail) {
if (_dataStore) {
success(_dataStore);
}
$http({
//fill in your params here
})
.then(
function successCallback(response) {
//store data in the _dataStore object
success(response)
}, fail(response))
},
_dataStore: {}
}
}
]);
app.controller('SampleACtrl', ['$scope', 'sampleFactory',
function($scope, sampleFactory) {
$scope.sampleA = sampleFactory.getData(success, fail);
}
]);
app.controller('SampleBCtrl', ['$scope', 'sampleFactory',
function($scope, sampleFactory) {
$scope.sampleB = sampleFactory.getData(success, fail);
}
]);
The main idea behind doing it like this is that you only make the HTTP request once, and then store the data in the factory as an object. When you call the getData() function on that object, you'll either get what is actually in the factory already (meaning the request was already made) or you'll go make the request. You'd pass in 2 functions (success or fail) as your response functions to the $http call. This is by far not 100% good, there's many improvements(add $q in there to return promises, etc) but it's a start in the right direction.
Long story short: USE FACTORIES!

How to get user by firstname using a $http service in angular js with Mongodb database

Hello I am trying to fetch a single user from my mongoDB database.
I have a service that works like this:
The service:
app.service('UsersService', function($http, $routeParams) {
var getAllUrl = '/users';
this.getSingleUser = function() {
return $http.get(getAllUrl/$routeParams.firstname)
.then(function(response) {
return response.data;
})
}
});
And then I have the controller.
The controller:
app.controller('singleContactCtrl',
function($scope, UsersService, $routeParams) {
// Get single contact
UsersService.getSingleUser().then(function(data) {
$scope.singlecontact = data;
});
});
On my api when I do /users/firstname I get my json data. Is there something I am doing wrong? Using the resource is quite straight forward but I would like to get some more insight on how the $http works.
I think the problem is the url getAllUrl/$routeParams.firstname should be changed to getAllUrl + '/' + $routeParams.firstname

Doing HTTP request on client-side using AngularJS

After successfully finishing this tutorial, I started building my app routes to handle the creation of some dummy models in the database, which works just fine when I request them through Postman app (using the follwing URL: https://lab4-roger13.c9users.io:8080/api/nerds).
The next step, was to create a service in AngularJS to allow the user to request those same informations at the client side. At the end of the tutorial I was left with this:
angular.module('NerdService', []).factory('Nerd', ['$http', function($http) {
return {
// call to get all nerds
get : function() {
return $http.get('/api/nerds');
},
a : 2,
// these will work when more API routes are defined on the Node side of things
// call to POST and create a new nerd
create : function(nerdData) {
return $http.post('/api/nerds', nerdData);
},
// call to DELETE a nerd
delete : function(id) {
return $http.delete('/api/nerds/' + id);
}
}
}]);
And this is the module that links all my services and routes:
angular.module('sampleApp',
['ngRoute', 'appRoutes', 'MainCtrl', 'NerdCtrl', 'NerdService'])
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
$scope.a = Nerd.a;
}]);
Here is a sample of a backend route I'm trying to access:
module.exports = function(app) {
// get all nerds in the database (accessed at GET https://lab4-roger13.c9users.io:8080/api/nerds)
app.get('/api/nerds', function(req, res) {
// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(nerds); // return all nerds in JSON format
});
});
As you can imagine, I can access the a property of the service at the html by using the {{a}} notation, which displays 2. But when I try the same with the get property, nothing shows up.
I'm not sure, is the URL the tutorial provides at the $http.get wrong or am I missing a step to do and access the GET response?
(If I missed any relevant code, they are the same as the ones that can be found at the tutorial link)
Nerd.get() is a function that returns a promise from the $http service. If you want to show it's result in your view, you can bind the results to your view like so:
.controller('nerdDB', ['$scope', 'Nerd', function($scope, Nerd) {
Nerd.get().then(function(nerds) {
$scope.nerds = nerds;
});
}]);
loved this post I had some problem using factory and found solution here
nerds controller
angular.module('NerdCtrl', []).controller('NerdController', function($scope, Nerd) {
$scope.tagline = 'bla bla';
$scope.nerds = {};
Nerd.getNerd()
.then(function (components) {
$scope.nerds = components;
}, function (error) {
console.error(error);
});
});
As service
angular.module('NerdService', []).factory('Nerd', function ($q, $http) {
return {
getNerd: function () {
var deferred = $q.defer(),
httpPromise = $http.get('/api/nerds');
httpPromise.success(function (components) {
deferred.resolve(components);
})
.error(function (error) {
console.error('Error: ' + error);
});
return deferred.promise;
}
};
});
In NerdHTLM using controller to loop records
<table ng-controller="NerdController" >
<tbody>
<tr ng-repeat="nerd in nerds">
<td>{{nerd.name}}</td>
<td>{{nerd.type}}</td>
</tr>
</tbody>
</table>

Resources