Hi I am new to angularjs and am trying to get some information from a service call using Restangular, I am facing trouble while retrieving the data. Following is the code for the js file
angular.module('sol.user', ['restangular'])
.controller('sol.user.UserController',UserController)
.factory('sol.user.UserFactory',UserFactory);
UserFactory.$inject =['$rootScope', 'Restangular'];
UserController.$inject =['$rootScope', 'Restangular','sol.user.UserFactory'];
function UserFactory($rootScope, Restangular) {
alert("1");
var UserController = {};
var userDetails = Restangular.one('/user/userDetails');
var a = userDetails.post();
UserController = a;
return UserController;
}
function UserController($rootScope, Restangular, user){
$state.go('home.search');
}
function RestConfig(RestangularProvider) {
RestangularProvider.setBaseUrl('http://10.98.3.2:9081/CustomerService/');
RestangularProvider.setDefaultHttpFields({cache: false,timeout: 20000});
RestangularProvider.setDefaultHeaders({brand: "wp",userBsb: "032000"});
;
RestangularProvider.setFullRequestInterceptor(RequestInterceptor);
}
I am not able to hit to the service url, while i am able to retrieve the data using RESTClient.
What seems to be the problem?
Also please tell me whats the difference between Restangular.all/one/
Related
I have an Umbraco project with an Area section configured with Angular.
I use the Plugins to integrate the Area with the use of package.manifest like this:
Into edit.controller.js, I have this script:
'use strict';
angular.module("umbraco")
.controller('Administration.AdministrationTree.EditController', function administrationEditController($scope, $routeParams, $http) {
//set a property on the scope equal to the current route id
$scope.id = $routeParams.id;
$scope.url = "";
$scope.canShow = false;
$scope.showIframe = function () {
if ($scope.url === "") {
return false;
}
return true;
};
$scope.canShow = false;
if (!$scope.id) {
return;
}
$http.get('/umbraco/backoffice/administration/CustomSection/GetUrl/?node=' + $scope.id)
.success(function (data) {
$scope.url = JSON.parse(data);
$scope.canShow = $scope.url;
});
});
When I run the project and click on any node in this area, I receive most of the time a 404 error like if the page was not exist. I say "most of the time" because 1 out of 10, it works and the page is displayed.
However, if I put a breakpoint in the javascript function below and I click on any node and resume the javascript after the breakpoint was hitting, the node related html page is displayed correctly.
Anybody know why when I put a breakpoint, Umbraco or Angular are able to resolve 100% of the time the page but not when I don't have any breakpoint in this function?
Thanks
I really hate to answer my own questions but after 2 weeks without answers and a lot of reflections on my side, I finally found a solution to this problem.
What was causing the problem of out synching between Umbraco and Angular was due to the $http.get query which is asynchronous with Angular (no other choice I think) and after a response from the server to get a valid URL, the $scope object was not able to talk to Umbraco to redirect to the valid URL.
On my asp.net MVC controller, the GetUrl function was trying to get a valid URL doing a query to the database where I keep a structure of nodes which correspond to a tree displayed to the user. This is a slow process and the time required to respond to the HTTP get request was too long the vast majority of the time.
Here is my solution to this problem:
'use strict';
var myCompany = myCompany || {};
myCompany.myProject = myCompany.myProject || {};
myCompany.myProject.controller = (function (parent){
parent.urls = {};
function loadUrls () {
$.get('/umbraco/backoffice/administration/CustomSection/GetUrls')
.success(function (data) {
parent.urls = data;
});
};
loadUrls();
return parent;
})({});
angular.module("umbraco")
.controller('Administration.AdministrationTree.EditController', function administrationEditController($scope, $routeParams, $http) {
//set a property on the scope equal to the current route id
$scope.id = $routeParams.id;
$scope.url = "";
$scope.canShow = false;
$scope.showIframe = function () {
if ($scope.url === "") {
return false;
}
return true;
};
$scope.canShow = false;
if (!$scope.id) {
return;
}
var url = myCompany.myProject.controller.urls.find(function (element) {
return element.Key == $scope.id;
});
if (url) $scope.url = url.Value;
$scope.canShow = $scope.url;
});
Note in this case that I have an iffe function which query the server to build an array of all my URLs from the backoffice and then when Angular need a redirection, I search directly from the array.
The iffe function is calling only once when the user enters in the backoffice section which I think is nice because the structure behind rarely changes.
I'm not sure if it's a hack or the valid way to do the thing due to my lack of experience with Angular but it works like a charm.
formApp.controller('load', function ($scope, ApiCall, $window, $http) {
$window.onload = function () {
alert("the page loaded and will now call the function");
ApiCall.GetApiCall("signOn", "GetSingleSignOn").success(function (data) {
alert("successful call to singleSignOn, GetSingleSignOn");
var data = $.parseJSON(JSON.parse(data));
$scope.apiGetInfo = data;
alert("successful call to singleSignOn, GetSingleSignOn");
alert(data);
});
};
This code works fine up to the var data- $.parseJson(JSON.parse(data));
I looked at some examples of how to do this in the Controller online and they all looked this way with $.parseJSON(JSON.parse(data)).
It gives me: ReferenceError: $ is not defined
Not sure why as every example I looked at to call an API Controller in Angular showed this way.
You don't need the $.parseJSON. remove it and leave the JSON.parse intact:
var data = JSON.parse(data);
If you want to use JQuery ($) you have to import the script.
UPDATE:
if you want to redirect to an URL you can use $window:
$window.location.href = 'http://www.google.com';
I have a loading problem in Firebase. I want to display a list of images when I open the view but nothing happens till i go back ( there is a flash and i can see my photo list). It's working but not displaying in the opening.
What am i missing please ?
There is the beginning of my Controller view:
'Use Strict';
angular.module('App').controller('valider_photosController', function($scope, $state, $localStorage, Popup, Firebase, $firebaseObject, $ionicHistory, $ionicPopup, $ionicModal, $cordovaCamera) {
$scope.imagestab = [];
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');
ref_logements.child(id_logement).child('images').on('child_added', added);
function added(idxSnap, prevId){
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
console.log('La valeur'+datasnap.key+'donne '+datasnap.val());
});
};
});
Since firebase works with asynchronous calls, by the time firebase responds with your data the angular cycle had already finished and you won't have your scope updated. You can force it by using $scope.$apply();.
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
$scope.$apply();
});
There is a tool that integrates angular and firebase in a way that you won't have to be concerned with things such as applying the scope. Its called angularfire. I totally recommend you to start using it in your application.
With angularfire you can get your data simply using
$scope.bidule = $firebaseObject(ref_images.child(idxSnap.key));
or
$scope.images = $firebaseArray(firebase.database().ref('images'));
I created a Factory
.factory('Firebase', function ($firebaseArray, $firebaseObject) {
var ref = firebase.database().ref();
return {
all: function (section) {
var data = $firebaseArray(ref.child(section));
return data;
},
getById: function (section, id) {
var data = $firebaseObject(ref.child(section).child(id));
return data;
},
get: function (section, field, value) {
var data = $firebaseArray(ref.child(section).orderByChild(field).equalTo(value));
return data;
}
};
})
And then in my controller, i replaced like you said :
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');
ref_logements.child(index2).child('images').on('child_added', added);
function added(idxSnap, prevId) {
var monimage = Firebase.getById('images', idxSnap.key);
$scope.imagestab.push(monimage);
};
And it Works like a charm ! Thank you again :)
I am working on displaying collection that I got from DB in angular with firebase DB. I have those controller and service setup. in the html, I use search.users expecting it will hold all the data that I got from the DB but it won't show up. I can't figure out why. I tried few things like angular.copy or $broadcast with no luck. Can anyone help advise on this? Appreciated in advance.
.controller('SearchController', function ($scope, SearchService, logout, $location){
var search = this;
search.users = SearchService.users;
//$scope.$on('evtputUsers', function () {
// search.users = SearchService.users;
//});
})
//service for SearchService
.factory('SearchService', function ($http, $rootScope){
var userRef = new Firebase("app url");
var broadcastUsers = function () {
$rootScope.$broadcast('evtputUsers');
};
//get the user info
//insert the data to the db.
//retrieving the data
var dbUsers;
userRef.child('users').on('value', function(snapshot){
dbUsers = snapshot.val();
// angular.copy(snapshot.val(), dbUsers);
console.log('usersinDB:',dbUsers);
broadcastUsers();
}, function(err){
console.error('an error occured>>>', err);
});
return {
users: dbUsers
};
})
Rather than using $broadcast() and $on() you should use the AngularFire module.
AngularFire provides you with a set of bindings to synchronizing data in Angular.
angular.module('app', ['firebase']) // 1
.controller('SearchCtrl', SearchCtrl);
function SearchCtrl($scope, $firebaseArray) {
var userRef = new Firebase("app url")
$scope.users = $firebaseArray(userRef); // 2
console.log($scope.users.length); // 3
}
There are three important things to take note of:
You need to include AngularFire as firebase in the dependency array.
The $firebaseArray() function will automagically synchronize your user ref data into an array. When the array is updated remotely it will trigger the $digest() loop for you and keep the page refreshed.
This array is asynchronous. It won't log anything until data has populated it. So if you're logs don't show anything initially, this is because the data is still downloading over the network.
I am trying to inject my Firebase Object to a service so I can use different Angular Controllers to access copies of the Firebase Object.
In a previous working copy of my app. I only loaded Firebase into a controller:
Example Below:
ToDo.controller('todoController',["$scope","$firebaseArray", function($scope, $firebaseArray, ToDoData){ // injecting AngularFire & ToDoData Service
var myData = new Firebase("https:firebase url goes here"); //create Firebase obj
$scope.todos = $firebaseArray(myData); //Reading Database and adding to todos variable
$scope.historytodos = [{'title': "Old Task", 'done':true, 'timetag':new Date().toString()}];
$scope.addTodo = function(){
var datecreated = new Date().toString();
$scope.todos.$add({'title':$scope.newtodo,'done':false, 'timetag': datecreated}); //push to Array
$scope.newtodo = '';
};
Now I am trying to recreate the Firebase Dependency , but to work with a service. Here is what I have for my attempted Service.
It is erroring this
Uncaught ReferenceError: Todo is not defined
Example of my Erroneous service :
Todo.value('fbURL', "https:firebase") //Firebase URL value service
.service('fbRef',function(fbURL){ //Firebase Data Reference Service
return new Firebase(fbURL);
})
.service('fbArr',function(fbRef){ //Firebase Array service
$scope.todos = $firebaseArray(fbRef);
return $scope.todos;
});
Not sure what's causing the error & also not too sure how to create a service to hold my Firebase object.
First of all the error is self explanatory, Todo is not defined. You have to do something like:
var Todo = {fbRef: "https:firebase"};
And for the service i suggest you read up on services and factory's to see what applies best for your particular case and here is a simple example of how to do it in a service:
.service('fb', function(){
var connection = new Firebase(url);
var todos = $firebaseArray(connection);
this.url = function() { return connection;};
this.todos = function() { return todos;};
});