i used a tutorial to create a angularfire chat app. it is a standalone app that uses ui-router. I integrated it succssfully as a view in my app but that is not practical. I need to be able to use the chat on any view I am at. I am stuck at moving a resolve function to a controller. I have read some docs and I believe it is returning a promise that I need to resolve in the controller. the link to the tutorial is here.
tutorial
here is the ui-router I am trying to get away from
.state('channels.direct', {
url: '/{uid}/messages/direct',
templateUrl: 'views/chat/_message.html',
controller: 'MessageController',
controllerAs: 'messageCtrl',
resolve: {
messages: function ($stateParams, MessageService, profile) {
return MessageService.forUsers($stateParams.uid, profile.$id).$loaded();
},
channelName: function ($stateParams, UserService) {
return UserService.all.$loaded().then(function () {
return '#' + UserService.getDisplayName($stateParams.uid);
});
}
}
})
The message service
var channelMessagesRef = new Firebase(AppConstant.FirebaseUrl + 'channelMessages');
var userMessagesRef = new Firebase(AppConstant.FirebaseUrl + 'userMessages')
return {
forChannel: function (channelId) {
return $firebaseArray(channelMessagesRef.child(channelId));
},
forUsers: function (uid1, uid2) {
var path = uid1 < uid2 ? uid1 + '/' + uid2 : uid2 + '/' + uid1;
return $firebaseArray(userMessagesRef.child(path));
}
};
the user service
var usersRef = new Firebase(AppConstant.FirebaseUrl + 'users');
var connectedRef = new Firebase(AppConstant.FirebaseUrl + '.info/connected');
var users = $firebaseArray(usersRef);
return {
setOnline: function (uid) {
var connected = $firebaseObject(connectedRef);
var online = $firebaseArray(usersRef.child(uid + '/online'));
connected.$watch(function () {
if (connected.$value === true) {
online.$add(true).then(function (connectedRef) {
connectedRef.onDisconnect().remove();
});
}
});
},
getGravatar: function (uid) {
return '//www.gravatar.com/avatar/' + users.$getRecord(uid).emailHash;
},
getProfile: function (uid) {
return $firebaseObject(usersRef.child(uid));
},
getDisplayName: function (uid) {
return users.$getRecord(uid).displayName;
},
all: users
};
here is what I have so far in the controller
$scope.directMessage = function (uid) {
UserService.all.$loaded().then(function () {
$scope.selectedChatUser = '#' + UserService.getDisplayName(uid);
});
$scope.selectedChatUserMessages = MessageService.forUsers(uid, profile.$id).$loaded();
};
I am returning the
$scope.selectedChatUser
fine. the issue is with the Message Service
this is the what i am currently returning from the message service
$$state: Object
__proto__: Promise
how do i resolve this?
You're trying to return from inside a promise in your channelName function.
The object you're getting back is an unresolved promise. You want the resolved data from the promise injected into your controller.
You need to create a to return from this function.
.state('channels.direct', {
url: '/{uid}/messages/direct',
templateUrl: 'views/chat/_message.html',
controller: 'MessageController',
controllerAs: 'messageCtrl',
resolve: {
messages: function ($stateParams, MessageService, profile) {
return MessageService.forUsers($stateParams.uid, profile.$id).$loaded();
},
channelName: function ($stateParams, UserService, $q) {
// create a deferred for this function
var deferred = $q.defer();
// load async data with UserService.all's promise
UserService.all.$loaded()
.then(function () {
var name = UserService.getDisplayName($stateParams.uid);
deferred.resolve(name);
});
// return promise
return deferred.promise;
}
}
})
However in getDisplayName I would just recommend returning back the object rather than just the name, as the entire set is synchronized by Firebase.
Related
I would like to use Angular 1.6.5 for a project rebuild, but I'm not sure how to use the $http.get request in a factory when the source returns only a limited number of records at a time (1000 returned per request) and there are over 2000 records that I need to get.
In my current code I use jquery ajax and in the .done method I check for the presence of the value "__next", and if it exists, I recall the function passing the value "__next". When the "__next" value isn't returned, I do something with the data.
function getSpecifiedList(url){
var specUrl = url;
$.ajax({
url: specUrl,
type: "GET",
headers:{"accept":"application/json;odata=verbose",
error: function(xhr){
console.log(xhr.status + " " + xhr.statusText);
}
}
}).done(function (results){
$("#wc_report_holder").text(results.length);
//buildObjects processes the results and adds to an array
buildObject(results);
if(results.d.__next){
getSpecifiedList(results.d.__next);
}else{
buildGridView();
}
}).fail(function(error){
$("#wc_report_holder").text("There was an error: " + error);
});
}
I would like to figure out how to implement that same value check and recursive call in angular 1.6.5 using best practice and most efficient but I haven't had luck figuring it out based on the angular docs and Googling.
Here is a short version of what I currently have using Angular 1.6.5.
<script>
var sitesApp = angular.module("sitesApp", ['ngRoute']);
sitesApp.controller('SitesListCtrl', ['$scope', 'sites',
function ($scope, sites) {
sites.list().then(function (response) {
$scope.sites = response.data.value;
});
}
]);
sitesApp.controller("SiteDetailsCtrl", ['$scope', '$routeParams', 'sites',
function ($scope, $routeParams, sites) {
sites.find($routeParams.SiteCodePc, function (site) {
$scope.site = site;
});
}
]);
sitesApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.
when('/', {
templateUrl: 'https://machine/sites/site-list.html',
controller: 'SitesListCtrl'
}).
when('/:SiteCodePc', {
templateUrl: 'https://machine/sites/site-details.html',
controller: 'SiteDetailsCtrl'
}).
otherwise({
redirectTo: '/'
});
});
sitesApp.factory('sites', ['$http', function ($http) {
var urlBase = "https://some-endpoint-for-data";
var cachedData;
function getData(callback) {
if (cachedData) {
callback(cachedData);
} else {
return $http({
method: 'GET',
url: urlBase
})
.then(function (response) {
//HERE IS WHERE I THINK THE SOLUTION NEEDS TO BE IMPLEMENTED
cachedData = response;
return cachedData;
});
}
}
return {
list: getData,
find: function (SiteCodePc, callback) {
getData(function (response) {
var site = response.data.value.filter(function (entry) {
//debugger;
return entry.SiteCodePc === SiteCodePc;
});
callback(site[0]);
});
}
};
}]);
</script>
<div ng-app="sitesApp">
<div ng-view></div>
</div>
Thanks in advance
It looks like you can do a simple recursion where you accept a second (optional) parameter. If you are calling getData() for the first time then you can get your first 1000 results. However if you find __next then you will call it again sending the current 1000 results you have and concat the next 1000 results with the previous 1000.
sitesApp.factory('sites', ['$http', function ($http) {
var urlBase = "https://some-endpoint-for-data";
function getData(callback, results) {
return $http({
method: 'GET',
url: urlBase
})
.then(function (response) {
// If you have found a previous batch of results then concat the two arrays
if(results) {
response = response.concat(results);
}
// If there are more results to be found then recursively call the same function passing the batched results
if(response.__next) {
return getData(callback, response);
}
// If there are no more results to be found then trigger your callback function
else {
callback(response);
}
});
}
return {
list: getData,
find: function (SiteCodePc, callback) {
getData(function (response) {
var site = response.data.value.filter(function (entry) {
//debugger;
return entry.SiteCodePc === SiteCodePc;
});
callback(site[0]);
});
}
};
}]);
I have implemented same kind of scenario with pagination logic and $q. In this sample code I am pulling the records recursively as lazy based on the LazyloadingLimit. You can specify the limit based on your requirement.So it only pulls the records based on the count from the total collection. In this below sample I am not using $http. On your real sample you can use the $http to pull the records from the server. Here I just hard coded the collection initially.
In your case you have to fetch total records count initially and apply some pagination logic or some other parameter to pull the next records.
angular.module('app', []);
angular.module('app').controller('SampleController', function ($scope,$http, $timeout, $q) {
// $scope.initialize();
$scope.mainCount = 0;
$scope.lazyloadingLimit = 2;
$scope.tileDefinitions = null;
$scope.tempList = null;
$scope.totalRecordCollection = [
{ "Name": "Record1" },
{ "Name": "Record2" },
{ "Name": "Record3" },
{ "Name": "Record4" },
{ "Name": "Record5" },
{ "Name": "Record6" },
{ "Name": "Record7" },
];
function getTotalRecordCollection() {
var deferred = $q.defer();
deferred.resolve($scope.totalRecordCollection);
return deferred.promise;
}
$scope.initialize = function () {
debugger;
var currentCount=0;
var pageList = new Array();
var currentPage = 1;
var numberPerPage = 2;
var numberOfPages = 0;
function makeList() {
numberOfPages = getNumberOfPages();
}
function getNumberOfPages() {
return Math.ceil($scope.tempList.length / numberPerPage);
}
function nextPage() {
currentPage += 1;
}
function loadList() {
var deferred = $q.defer();
if (currentCount !== $scope.tempList.length) {
var begin = ((currentPage - 1) * numberPerPage);
var end = begin + numberPerPage;
pageList = $scope.tempList.slice(begin, end);
currentCount = currentCount + pageList.length;
$scope.mainCount = currentCount;
deferred.resolve(true);
} else {
debugger;
return $q.reject();
}
return deferred.promise;
}
function loadNextRecords() {
loadList().then(function (res) {
nextPage();
loadNextRecords();
});
}
getTotalRecordCollection().then(function (response) {
debugger;
$scope.tempList = response;
makeList();
loadNextRecords();
});
}
});
<body ng-controller="SampleController">
<input type="button" value="Click Here" ng-click="initialize()"/>
{{mainCount}}
</body>
Once all the records are loaded , you should reject the promise else the recursive loops never end.
Hope this helps
I have this problem using resolve with component & ui-router, the data "after" resolving promise are "undefined" in a controller
Service:
class userService {
constructor ($http, ConfigService, authService) {
this.$http = $http;
this.API_URL = `${ConfigService.apiBase}`;
this.authService = authService;
}
testAuth () {
return this.$http.get(this.API_URL + '/test-auth')
}
getCollaboratores () {
return this.$http.get(this.API_URL + '/collaboratores').then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
}
)
}
getAccount () {
var config = {
headers: { "X-Shark-CollaboratoreId" : "1"}
};
return this.$http.get(this.API_URL + '/accounts' + '/' + 1, config).then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
}
)
}
Module/Component/Routing:
.config(($stateProvider, $urlRouterProvider) => {
"ngInject";
$urlRouterProvider.otherwise('/');
$stateProvider
.state('core', {
redirectTo: 'dashboard',
url: '/core',
component: 'core',
resolve: {
userdata: (userService) => {
return userService.getCollaboratores();
},
accdata: (userService) => {
return userService.getAccount();
}
}
});
})
Controller:
let self;
class CoreController {
constructor($state,userService,authService,userdata,accdata) {
this.name = 'core';
this.$state = $state;
this.userService = userService;
this.authService = authService;
this.userdata = userdata;
this.accdata = accdata;
console.log('name',this.name);
self = this;
console.log('userdata',self);
}
}
CoreController.$inject = ['$state','userService', 'authService','userdata','accdata'];
export default CoreController;
After injecting in the controller the object "resolved" by promise after "http" call
this.userdata = userdata;
this.accdata = accdata;
are undefined!!!
where is the bug.??
thanks a lot...
Change the getCollaboratores function to below :
getCollaboratores () {
return this.$http.get(this.API_URL + '/collaboratores').then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
return resolve;
});
}
Do the same with other one getAccount (i.e inside the success callback return resolve).
This will solve your problem.
Reason is once you chain success callbacks, 1st callback as to return the something which can be the arguments for the 2nd callback. Since the success callback in service was not returning anything(default return value of a function in js is undefined), hence resolved value was not available in the controller.
What version of angularjs are you using?
Remember that in 1.6, a then callback now receives 4 parameters: data, status, headers, config and statusText.
In this scenario, a resolve.data could result in an undefined value.
More info on docs: https://docs.angularjs.org/api/ng/service/$http
I see that you relate to a component in your state not to a controller, so you should create a component and bind the resolved values to it.
angular
.module('app')
.component('core', {
templateUrl: 'app/app.html',
controller: CoreController,
controllerAs: 'vm',
bindings: {
userdata: '<',
accdata: '<'
}
});
And to get the resolve data in your component controller do this:
const vm = this;
vm.$onInit = () => {
console.log('userdata: ', vm.userdata);
console.log('accdata: ', vm.accdata);
}
I have this script in my app.js:
app.run(['$http', '$location', 'myAppConfig', function ($http, $location, myAppConfig) {
if (myAppConfig.webAPIPath.main == '') {
var getconfigDone = false;
$http.get('fileHandler.ashx?action=getconfig')
.then(function (result) {
if (JSON.parse(result.data.Data).APIURL !== undefined && JSON.parse(result.data.Data).APIURL != '') {
var apiURL = JSON.parse(result.data.Data).APIURL;
if (apiURL.lastIndexOf('/') + 1 == apiURL.length) {
apiURL = apiURL.substring(0, apiURL.lastIndexOf('/'))
}
myAppConfig.webAPIPath.main = apiURL + "/";
myAppConfig.webAPIPath.account = myAppConfig.webAPIPath.main + '/api/OnlineApplicationPortal/v1/Account/';
myAppConfig.webAPIPath.dashboard = myAppConfig.webAPIPath.main + '/OnlineApplicationPortal/v1/Dashboard/';
}
else {
$location.path('Action/Welcome/apiUrlError');
}
//debugger
getconfigDone = true;
}, function (response) { debugger }
);
}
}]);
Also I have got this factory object which uses the myAppConfig in app.js:
(function () {
angular
.module('app.data')
.factory('accountDS', ['$http', '$routeParams', 'myAppConfig', function ($http, $routeParams, myAppConfig) {
var pathPrefix = myAppConfig.webAPIPath.account;
var createAccount = function (account, email) {
var OnlineApplicationPortalModel = {
Name: account.firstName,
Surname: account.lastName,
Email: email,
Password: account.password
};
return $http.post(pathPrefix + 'CreateAccount', OnlineApplicationPortalModel)
.then(function (response) {
return response;
});
};
var confirmEmail = function () {
var data = {
guid: $routeParams.guid
};
return $http.post(pathPrefix + 'ConfirmEmail', data)
.then(function (response) {
return response;
});
}
return {
createAccount: createAccount,
confirmEmail: confirmEmail
};
}]);
})();
The service object needs to use myAppConfig.webAPIPath.account which is resolved in the function in app.js run function. Now the problem is sometimes the browser reaches the service code sooner than than the AJAX call is returned, a race condition. I know that it is not possible in AngularJS to make a sync AJAX call. So how can I solve this?
If I correctly understand you, you want to myAppConfig.webAPIPath.account resolve this value to use it later in your code, but ajax call which provides you value for this variable is not always called before assignment. I think you could use https://docs.angularjs.org/api/ng/service/$q to solve your problem. Your code in myAppConfig should be inside function, so you can call it inside your factory and return deferred object, which then when your .account variable is set should call code from accountDS factory.
I need to fetch some data before allowing the page to render so that the page isn't empty for a second before showing the info. But I'm unable to get my resolve to work.
The issue is that the uid line throws an error because states.getAuth() is undefined. states.getAuth() should (and does) return authentication info about the user when using it from my controllers but when using it in this resolve it doesn't for some reason.
Am I going about this completely wrong? I have never had to do a resolve like this before so I wouldn't know so some guidance would be great.
Let me know if I have to include any of my services or if this route snippet is enough to figure out a solution.
.when('/programs/:program', {
templateUrl: 'views/pages/single-program.html',
resolve: {
'isAuth': ['fbRefs', function(fbRefs) {
return fbRefs.getAuthObj().$requireAuth();
}],
'programData': ['$route', 'fbRefs', 'states', function($route, fbRefs, states) {
// Get our program key from $routeParams
var key = $route.current.params.program;
// Get unique user id
var uid = states.getAuth().uid; // Throws error
// Define our path
var path = uid + '/programs/' + key;
// Fetch the program from Firebase
var program = fbRefs.getSyncedObj(path).$loaded();
return program;
}]
}
})
Added states service code by request:
auth.service('states', [function() {
var auth;
return {
getAuth: function() {
return auth;
},
setAuth: function(state) {
auth = state;
}
};
}]);
You are using the 'Service Recipe' to create the states service, but returning like a 'Factory Recipe'.
According to the doc:
https://docs.angularjs.org/guide/providers#service-recipe
You should either use this:
auth.factory('states', [function() {
var auth;
return {
getAuth: function() {
return auth;
},
setAuth: function(state) {
auth = state;
}
};
}]);
Or this:
auth.service('states', [function() {
var auth;
this.getAuth = function() {
return auth;
};
this.setAuth = function(state) {
auth = state;
};
}]);
I am learning how to use resolve from an example, and applying it on to my Todo script.
Then I realised an issue, that the example is only showing me how to resolve GET call to get me the Todo List when I first visit this route.
However, in the same route same page I have an Add button to POST new todo item, also a Clear button to DELETE completed items.
Looking at my $scope.addTodo = function() { and $scope.clearCompleted = function () { I want to Resolve my TodoList again after the action. How can I do that?
Here is my code. In my code, the initial resolve: { todos: TodosListResl } is working, it hits TodosListResl function and produces the promise. However, I don't know what to do with addTodo and clearComplete when I want to resolve the todo list again.
main.js
var todoApp = angular.module('TodoApp', ['ngResource', 'ui']);
todoApp.value('restTodo', 'api/1/todo/:id');
todoApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when("/", { templateUrl: "Templates/_TodosList.html",
controller: TodosListCtrl, resolve: { todos: TodosListResl } });
$routeProvider.otherwise({ redirectTo: '/' });
});
//copied from example, works great
function TodoCtrl($scope, $rootScope, $location) {
$scope.alertMessage = "Welcome";
$scope.alertClass = "alert-info hide";
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$scope.alertMessage = "Loading...";
$scope.alertClass = "progress-striped active progress-warning alert-info";
});
$rootScope.$on("$routeChangeSuccess", function (event, current, previous) {
$scope.alertMessage = "OK";
$scope.alertClass = "progress-success alert-success hide";
$scope.newLocation = $location.path();
});
$rootScope.$on("$routeChangeError",
function (event, current, previous, rejection) {
alert("ROUTE CHANGE ERROR: " + rejection);
$scope.alertMessage = "Failed";
$scope.alertClass = "progress-danger alert-error";
});
}
//also copied from example, works great.
function TodosListResl($q, $route, $timeout, $resource, restTodo) {
var deferred = $q.defer();
var successCb = function(resp) {
if(resp.responseStatus.errorCode) {
deferred.reject(resp.responseStatus.message);
} else {
deferred.resolve(resp);
}
};
$resource(restTodo).get({}, successCb);
return deferred.promise;
}
//now, problem is here in addTodo and clearCompleted functions,
//how do I call resolve to refresh my Todo List again?
function TodosListCtrl($scope, $resource, restTodo, todos) {
$scope.src = $resource(restTodo);
$scope.todos = todos;
$scope.totalTodos = ($scope.todos.result) ? $scope.todos.result.length : 0;
$scope.addTodo = function() {
$scope.src.save({ order: $scope.neworder,
content: $scope.newcontent,
done: false });
//successful callback, but how do I 'resolve' it?
};
$scope.clearCompleted = function () {
var arr = [];
_.each($scope.todos.result, function(todo) {
if(todo.done) arr.push(todo.id);
});
if (arr.length > 0) $scope.src.delete({ ids: arr });
//successful callback, but how do I 'resolve' it?
};
}
I think you're missing the point of resolve. The point of resolve is to " delay route change until data is loaded. In your case, you are already on a route, and you want to stay on that route. But, you want to update the todos variable on the successful callback. In this case, you don't want to use resolve. Instead, just do what needs to be done. For example
$scope.addTodo = function() {
$scope.src.save({ order: $scope.neworder,
content: $scope.newcontent,
done: false }, function () {
todos.push({ order: $scope.neworder,
content: $scope.newcontent,
done: false });
});
//successful callback, but how do I 'resolve' it?
};
As a side point, I noticed you're using _ most likely from the Underscore library. You don't need to use another library for that because Angular already has $angular.forEach().