On the server side, I'm using Web API with the OData routing convention, which means that my route for getting a single entity looks something like this:
/api/v1/Products(1)
rather than:
/api/v1/Products/1
Normally, in Restangular, I'd be able to get a single entity with something like this:
Restangular.one('Product', 1);
But that doesn't work for my OData endpoint. I've looked at customGET, and setRequestInterceptor but I can't seem to find an example of or figure out how to change the route to match my endpoint. Preferably globally since all of my entities will have this same format.
Any help is greatly appreciated.
Restangular documentation details how to create a custom configuration, you could do the same by editing the source restangular.js but this extensibility point allows us to keep a clean implementation that should be compatible with most customisations or future versions of RestAngular as well as allowing side-by-side standard REST APIs and OData v4 APIs.
How to create a Restangular service with a different configuration from the global one
// Global configuration
app.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost:16486');
RestangularProvider.setRestangularFields({ id: 'Id' });
});
// Restangular service targeting OData v4 on a the specified route
app.factory('ODataRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl(RestangularConfigurer.baseUrl + '/odata');
// OData v4 controller(key) Item Route convention
RestangularConfigurer.urlCreatorFactory.path.prototype.base = function(current) {
var __this = this;
return _.reduce(this.parentsArray(current), function(acum, elem) {
var elemUrl;
var elemSelfLink = RestangularConfigurer.getUrlFromElem(elem);
if (elemSelfLink) {
if (RestangularConfigurer.isAbsoluteUrl(elemSelfLink)) {
return elemSelfLink;
} else {
elemUrl = elemSelfLink;
}
} else {
elemUrl = elem[RestangularConfigurer.restangularFields.route];
if (elem[RestangularConfigurer.restangularFields.restangularCollection]) {
var ids = elem[RestangularConfigurer.restangularFields.ids];
if (ids) {
// Crude Implementation of 'several', don't try this with more than
// 60 Ids, performance degrades exponentially for large lists of ids.
elemUrl += '?$filter=((Id eq ' + ids.join(')or(Id eq ') + '))';
}
} else {
var elemId;
if (RestangularConfigurer.useCannonicalId) {
elemId = RestangularConfigurer.getCannonicalIdFromElem(elem);
} else {
elemId = RestangularConfigurer.getIdFromElem(elem);
}
if (RestangularConfigurer.isValidId(elemId) && !elem.singleOne) {
elemUrl += '(' + (RestangularConfigurer.encodeIds ? encodeURIComponent(elemId) : elemId) + ')';
}
}
}
acum = acum.replace(/\/$/, '') + '/' + elemUrl;
return __this.normalizeUrl(acum);
}, RestangularConfigurer.baseUrl);
};
// add a response interceptor for OData v4:
RestangularConfigurer.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// Collection requests are 'getList' operations
if (operation === "getList") {
// return the value array
extractedData = data.value;
} else {
// return the first item in the array
if(data.value.length > 0)
extractedData = data.value[0];
}
// pass the metadata back
if(extractedData) {
extractedData.meta = { context: data['#odata.context'] };
if(data['#odata.count'])
extractedData.meta.count = data['#odata.count'];
}
return extractedData;
});
});
});
Implementation example:
// Controller for list route
function ListCtrl($scope, ODataRestangular) {
$scope.providers = ODataRestangular.all("providers").getList({ $count:true }).$object;
$scope.some = ODataRestangular.several("providers", 15,16,17,18).getList();
$scope.single = ODataRestangular.one("providers", 15).get();
}
Captured URLs from network Traffic:
http://localhost:16486/odata/providers?$count=true
http://localhost:16486/odata/providers?$filter=((Id eq 15)or(Id eq 16)or(Id eq 17)or(Id eq 18))
http://localhost:16486/odata/providers(15)
I struggled to try to write a custom service factory and to modify BreezeJS to work with OData v4 and only recently stumbled into Restangular, I can now really appreciate the extensible design that went into restangular, the general lack of documented client side framework support has been the Achilles heel that has prevented a wider adoption of OData v4. I hope this answer contributes to getting more developers onboard with version 4.
Restangular does not explicitly support OData APIs. You can make the basics work, but you would probably be better off using a library that does support querying an OData API, like breeze.js.
Related
i am very new to pouchdb, meaning i have not yet been successfully able to implement an app that uses it.
This is my issue now, in my controller i have two functions:
var init = function() {
vm.getInvoicesRemote(); // Get Data from server and update pouchDB
vm.getInvoicesLocal(); // Get Data from pouchDB and load in view
}
init();
Basically in my app i have a view that shows customer invoices, now i want customers to be able to still see those invoices when they're offline. I have seen several examples of pouchdb and couchdb but all use the "todo" example which does not really give much information.
Now i'm just confused about what the point was in me spending hours understanding couchdb and installing it if in the end i'm just going to be retrieving the data from my server using my API.
Also when the data is returned how does pouchdb identify which records are new and which records are old when appending.
well, i m working on same kind..!this is how i m making it work..!
$scope.Lists = function () {
if(!$rootScope.connectionFlag){
OfflineService.getLocalOrdersList(function (localList) {
if(localList.length > 0) {
$scope.List = localList;
}
});
}else{
if(!$scope.user){
}else {
Common.callAPI("post", '***/*************', $scope.listParams, function (data) {
if (data !== null) {
$scope.List = data.result;
OfflineService.bulkOrdersAdd_updateLocalDB($scope.List);
}
});
}
}
};
so,$scope.List will be filled if online as well as offline based on connectionFlag
note : OfflineService and Common are services.
call method:
$ionicPlatform.ready(function () {
OfflineService.configDbsCallback(function(res) {
if(res) {
$scope.Lists();
}
});
});
u can try calling $scope.Lists(); directly..!
hope this helps u..!
I am trying to build an app with angularjs and Firebase similar to a forum for helping my classmates with problems. I also want people to be able to 'reply' to the specific problems the classmates are having, so I create an object with many values in the angularjs factory, like this:
factory.addError = function() {
factory.errors.$add({
...
replies: []
});
};
The problem with this is that Firebase doesn't save parameters with empty values for placeholders, such as the parameter 'replies' above. I have tried to hard code a placeholder value into the array, but that seems like a very patchy solution, and that comes with it's own set of problems for me having to delete out the data in Firebase. For reference, here is the code in the linked controller:
$scope.error.replies.$push({
name: $scope.replyName,
message: $scope.replyMessage,
time: (new Date()).toString(),
upvote: 0
});
How do you initialize an empty array into the object? And will $push properly use Firebase's commands to save it to it's own set of data?
First, here are some relevant resources and suggestions:
Resources
Check out Firebase's blog post, Best Practices: Arrays in Firebase - "Arrays are evil".
Also, the AngularFire Development Guide.
And the documentation for AngularJS providers.
Suggestions
As the AngularFire API Documentation says:
"There are several powerful techniques for transforming the data downloaded and saved by $firebaseArray and $firebaseObject. These techniques should only be attempted by advanced Angular users who know their way around the code."
Putting all that together, you accomplish what you want to do by:
Extending AngularFire services, $firebaseArray and $firebaseObject.
Following the documentation for extending services.
Example
Extended Error $firebaseObject
.factory('Error', function(fbUrl, ErrorFactory) {
return function(errorKey){
var errorRef;
if(errorKey){
// Get/set Error by key
errorRef = new Firebase(fbUrl + '/errors/'+errorKey);
} else {
// Create a new Error
var errorsListRef = new Firebase(fbUrl + '/errors');
errorRef = errorsListRef.push();
}
return new ErrorFactory(errorRef);
}
})
.factory('ErrorFactory', function($firebaseObject){
return $firebaseObject.$extend({
sendReply: function(replyObject) {
if(replyObject.message.isNotEmpty()) {
this.$ref().child('replies').push(replyObject);
} else {
alert("You need to enter a message.");
}
}
});
})
Error Controller
.controller('ErrorController',function($scope, Error) {
// Set empty reply message
$scope.replyMessage = '';
// Create a new Error $firebaseObject
var error = new Error();
$scope.error = error;
// Send reply to error
$scope.reply = function(){
error.sendReply({message:$scope.replyMessage});
}
})
And String.prototype.isNotEmpty()
String.prototype.isNotEmpty = function() {
return (this.length !== 0 && this.trim());
};
(adapted from this answer)
Hope that helps!
I'm learning AngularJS , i set-up a development environment using sublime-text as editor and parse.com-rest-api used as back-end layer.
I came across a scenario where, I have to fetch data based on an attribute.
Below given code from the service layer of angularjs has fetch all records from table 'filim'.
var config = {
headers: {
'X-Parse-Application-Id': 'bNtp8FUfr0s1UsAwJr7MFjabCI31HytIuC3gCaJ2',
'X-Parse-REST-API-Key': 'g18cAoH7QkrBZenPqH0pynMKsn6pj4MyfDyIy6X1',
}
};
return {
getFilims: function(callback) {
var filims;
var resp = $http.get('https://api.parse.com/1/classes/filim', config).success(function(data) {
callback(data.results);
});
}
}
I have modified above url to send query-parameter to filter the output, but did not work.
I refer parse.com api doc [ https://www.parse.com/docs/rest#queries ] to modify url to send query - param.
Modified code is given below,
var params = {"where": {"status" : "CLOSED" } }
var resp = $http.get('https://api.parse.com/1/classes/filim?%s' % params, config).success(function(data) {
callback(data.results);
});
But this did not work.
Is this the way to use query-parameter ?
Regards
Ajil
'https://api.parse.com/1/classes/filim?%s' % params
This is a python pattern for interpolating strings and will not work in javascript.
The correct way of combining strings in javascript is:
'https://api.parse.com/1/classes/filim?' + params
Even still, that will probably not work because you'll end up with something like:
'https://api.parse.com/1/classes/filim?[Object object]
What you need to do for parse.com is to JSON encode the query, so try this:
var whereQuery = {"status" : "CLOSED"};
var url = 'https://api.parse.com/1/classes/filim?where=' + encodeURI(JSON.stringify(whereQuery));
var resp = $http.get(url, config).success(function(data) {
callback(data.results);
});
I am trying to build an Angular project with Pusher using the angular-pusher wrapper. It's working well but I need to detect when the user loses internet briefly so that they can retrieve missed changes to data from my server.
It looks like the way to handle this is to reload the data on Pusher.connection.state('connected'...) but this does not seem to work with angular-pusher - I am receiving "Pusher.connection" is undefined.
Here is my code:
angular.module('respondersapp', ['doowb.angular-pusher']).
config(['PusherServiceProvider',
function(PusherServiceProvider) {
PusherServiceProvider
.setToken('Foooooooo')
.setOptions({});
}
]);
var ResponderController = function($scope, $http, Pusher) {
$scope.responders = [];
Pusher.subscribe('responders', 'status', function (item) {
// an item was updated. find it in our list and update it.
var found = false;
for (var i = 0; i < $scope.responders.length; i++) {
if ($scope.responders[i].id === item.id) {
found = true;
$scope.responders[i] = item;
break;
}
}
if (!found) {
$scope.responders.push(item);
}
});
Pusher.subscribe('responders', 'unavail', function(item) {
$scope.responders.splice($scope.responders.indexOf(item), 1);
});
var retrieveResponders = function () {
// get a list of responders from the api located at '/api/responders'
console.log('getting responders');
$http.get('/app/dashboard/avail-responders')
.success(function (responders) {
$scope.responders = responders;
});
};
$scope.updateItem = function (item) {
console.log('updating item');
$http.post('/api/responders', item);
};
// load the responders
retrieveResponders();
};
Under this setup how would I go about monitoring connection state? I'm basically trying to replicate the Firebase "catch up" functionality for spotty connections, Firebase was not working overall for me, too confusing trying to manage multiple data sets (not looking to replace back-end at all).
Thanks!
It looks like the Pusher dependency only exposes subscribe and unsubscribe. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L86
However, if you access the PusherService you get access to the Pusher instance (the one provided by the Pusher JS library) using PusherService.then. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L91
I'm not sure why the PusherService provides a level of abstraction and why it doesn't just return the pusher instance. It's probably so that it can add some of the Angular specific functionality ($rootScope.$broadcast and $rootScope.$digest).
Maybe you can set the PusherService as a dependency and access the pusher instance using the following?
PusherService.then(function (pusher) {
var state = pusher.connection.state;
});
To clarify #leggetters answer, you might do something like:
app.controller("MyController", function(PusherService) {
PusherService.then(function(pusher) {
pusher.connection.bind("state_change", function(states) {
console.log("Pusher's state changed from %o to %o", states.previous, states.current);
});
});
});
Also note that pusher-js (which angular-pusher uses) has activityTimeout and pongTimeout configuration to tweak the connection state detection.
From my limited experiments, connection states can't be relied on. With the default values, you can go offline for many seconds and then back online without them being any the wiser.
Even if you lower the configuration values, someone could probably drop offline for just a millisecond and miss a message if they're unlucky.
I have downloaded the sample 'Breeze 0.83.5' applications from http://www.breezejs.com/documentation/download
The Angular 'ToDo' sample does not work with IE8.
I have included the following script references above my Breeze script reference.
Any idea why this doesn't work?
Breeze's Angular support makes use of the 'backingStoreAdapter' which in turn depends on the ES5 Javascript 'defineProperty' method being implemented by the browser. This was not implemented in IE8, and unfortunately, cannot be supplemented via the use of a shim.
This is the only adapter that has this limitation, the breeze knockout and backbone adapters, both work with IE8 with the use of ES5 shims.
Sorry!
It will not work on IE8 in the future versions of Breeze neither.
Todo-Angular runs in modern browsers such as IE9, IE10, and recent
Chrome, Safari, Firefox, and WebKit browsers. Breeze does not support
AngularJS apps running in older browsers that lack ECMAScript 5
property getters and setters.
Breeze uses the ViewModel of the hosting MVVM framework. That’s generally a good decision. Additionally, change tracking on entities is a fundamental concept of breeze.js (same for Entity Framework). It’s an easy task to track changes if the MVVM framework uses Observables with real getter and setters (e.g. Knockout). AngularJS on the other hands works with plain JavaScript objects. This makes change tracking difficulty. The only two reliable ways are ES5-properties (simple, but not supported by IE8) or a very deep integration in the $digest cycle. The breeze-team took the first-choice - what a pity for projects that have to support IE8!
Ok, let's analyze the root cause of the problem: change tracking
Do you really need that feature? At least in our project we decided for breeze.js/OData for reading and for a more "restful" approach when it comes to writing. If you don’t need those advanced features, than the following script should solve the issue:
/********************************************************
* A replacement for the "backingStore" modelLibrary
*
* This is a bare version of the original backingStore,
* without ANY change tracking - that's why it will work in IE8!
* (Object.defineProperty not required any more)
*
* This adapter is a "drop in" replacement for the "backingStore" adapter in Breeze core.
* It has the same adapter name so it will silently replace the original "backingStore" adapter
* when you load this script AFTER the breeze library.
* WARNING: For obvious reasons a lot of breeze magic will be lost!
*
* Author: Johannes Hoppe / haushoppe-its.de
*
* Copyright 2014 IdeaBlade, Inc. All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the IdeaBlade Breeze license, available at http://www.breezejs.com/license
******************************************************/
(function (definition, window) {
if (window.breeze) {
definition(window.breeze);
} else if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// CommonJS or Node
var b = require('breeze');
definition(b);
} else if (typeof define === "function" && define["amd"] && !window.breeze) {
// Requirejs / AMD
define(['breeze'], definition);
} else {
throw new Error("Can't find breeze");
}
}(function (breeze) {
"use strict";
var core = breeze.core;
var ctor = function () {
this.name = "backingStore";
this.A_BIG_FAT_WARNING = "This is a bare version of the backingStore! Change tracking won't work!";
};
var protoFn = ctor.prototype;
protoFn.initialize = function() {
};
protoFn.getTrackablePropertyNames = function (entity) {
var names = [];
for (var p in entity) {
if (p === "entityType") continue;
if (p === "_$typeName") continue;
var val = entity[p];
if (!core.isFunction(val)) {
names.push(p);
}
}
return names;
};
protoFn.initializeEntityPrototype = function (proto) {
proto.getProperty = function (propertyName) {
return this[propertyName];
};
proto.setProperty = function (propertyName, value) {
this[propertyName] = value;
return this;
};
};
// This method is called when an EntityAspect is first created - this will occur as part of the entityType.createEntity call.
// which can be called either directly or via standard query materialization
// entity is either an entity or a complexObject
protoFn.startTracking = function (entity, proto) {
// assign default values to the entity
var stype = entity.entityType || entity.complexType;
stype.getProperties().forEach(function (prop) {
var propName = prop.name;
var val = entity[propName];
if (prop.isDataProperty) {
if (prop.isComplexProperty) {
if (prop.isScalar) {
val = prop.dataType._createInstanceCore(entity, prop);
} else {
val = breeze.makeComplexArray([], entity, prop);
}
} else if (!prop.isScalar) {
val = breeze.makePrimitiveArray([], entity, prop);
} else if (val === undefined) {
val = prop.defaultValue;
}
} else if (prop.isNavigationProperty) {
if (val !== undefined) {
throw new Error("Cannot assign a navigation property in an entity ctor.: " + prop.Name);
}
if (prop.isScalar) {
// TODO: change this to nullstob later.
val = null;
} else {
val = breeze.makeRelationArray([], entity, prop);
}
} else {
throw new Error("unknown property: " + propName);
}
entity[propName] = val;
});
};
breeze.config.registerAdapter("modelLibrary", ctor);
}, this));
Download at: https://gist.github.com/JohannesHoppe/72d7916aeb08897bd256
This is a bare version of the original backingStore, without ANY change tracking - that's why it will work in IE8! (Object.defineProperty not required any more) This adapter is a "drop in" replacement for the "backingStore" adapter in Breeze core. It has the same adapter name so it will silently replace the original "backingStore" adapter when you load the script AFTER the breeze library.
Here is a demo to proof the functionality:
http://jsfiddle.net/Johannes_Hoppe/bcav9hzL/5/
JsFiddle does not support IE8, please use this direct link:
http://jsfiddle.net/Johannes_Hoppe/bcav9hzL/5/embedded/result/
Cheers!