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

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.

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 post data from angular service to laravel controller

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

{"error":"An invalid API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of 2.0.0."}

I recently received this error when trying to sign up on my application.
{"error":"An invalid API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of 2.0.0."}
It worked before and this is a very recent error
controller file...
.controller('signupCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {
$scope.User = {};
$scope.loadUser = function() {
var client = new WindowsAzure.MobileServiceClient('azure client');
var item = { FirstName: $scope.User.FirstName, LastName: $scope.User.LastName, Birthday: $scope.User.Birthday, PhoneNumber: $scope.User.PhoneNumber, Email: $scope.User.Email, StudentID: $scope.User.StudentID, GradeYear: $scope.User.GradeYear, ParentalGuardian: $scope.User.ParentalGuardian, ParentalGuardian2: $scope.User.ParentalGuardian2, PG1Number: $scope.User.GuardianNumber, PG2Number: $scope.User.GuardianNumber2, PG1Email: $scope.User.GuardianEmail, PG2Email: $scope.User.GuardianEmail2, Password: $scope.User.Password};
client.getTable('clubUser').insert(item);
};
}])
.controller('loginCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {
$scope.User = {};
$scope.login = function() {
var client = new WindowsAzure.MobileServiceClient('azure client');
client.getTable('clubUser')
.where({ EMAIL: $scope.User.email, PASSWORD: $scope.User.password })
.read()
.then(function() {
console.log('It Worked');
$state.go("tabsController.qRCode");
}, function(error) {
console.log('an error occurred while checking login:');
console.dir(error);
});
};
}])
You need to add API version to your API call. You can add it as a querystring
?ZUMO-API-VERSION=2.0.0
Or as an http header
HEADERS: ZUMO-API-VERSION: 2.0.0
More info: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-client-and-server-versioning
It randomly started working again... Maybe my server was updating or my studio was. Thank you for the help

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!

Angularjs cannot get data from service

I'm trying to pass data from one controller to another using a service, however no matter what I'm trying it always returns 'undefined' on the second controller. Here is my service :
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);
Here is controller1 :
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);
And then controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);
That is simple code, unfortunately I've been struggling for a few hours now, any suggestion ? Thanks.
Created a fiddle here:
http://jsfiddle.net/frishi/8yn3nhfw/16
To isolate the problem, can you remove the dependencies from the definition for myService and see if that makes it work? Look at the console after you load the fiddle.
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})
I assume the issue is that you are returning this.savedData in the service. Try returning savedData.
this behaves different in Javascript than in other languages.

Resources