I am using msal.js and wanted to use domain_hint to land directly on IdP page. After I set extraQueryParameters: {domain_hint: 'abc'}
msal.js does add the domain_hint=xyz to the query string but it is also adding domain domain_hint=organizations before that which led B2C to show the IdP selection page that I like to skip.
URL
https://xyz.b2clogin.com/xyz.onmicrosoft.com/b2csignupsignin/oauth2/v2.0/authorize?response_type=id_token&scope=https%3A%2F%test.onmicrosoft.com%2Fhelloapi%2Fdemo.read%20openid%20profile&client_id=e3443e90-18bc-4a23-9982-7fd5e67ff339&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&state=11eff659-29d9-49af-80db-a7ef5bfe55ee&nonce=daeafcda-5984-468b-8796-1b2655a8599e&client_info=1&x-client-SKU=MSAL.JS&x-client-Ver=1.1.2&login_req=9b8396fa-6441-466d-98da-3efd87ab7d07-b2c_1_primerosignupsignin&domain_req=48e05529-88b8-40e1-825a-18c4e1077b3a&domain_hint=organizations&domain_hint=abc&client-request-id=f2e88cb1-5edb-447f-8fc3-578f69c23b4e&response_mode=fragment
Index.html
<head>
<title>Calling a Web API as a user authenticated with Msal.js app</title>
<style>
.hidden {
visibility: hidden
}
.visible {
visibility: visible
}
.response {
border: solid;
border-width: thin;
background-color: azure;
padding: 2px;
}
</style>
</head>
<body>
<!-- bluebird only needed if this page needs to run on Internet Explorer -->
<!-- msal.min.js can be used in the place of msal.js; included msal.js to make debug easy -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js" class="pre"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.1.2/js/msal.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" class="pre"></script>
<h2>Getting an access token with Azure AD B2C and calling a Web API</h2>
<div>
<div id="label">Sign-in with Microsoft Azure AD B2C</div>
<button id="auth" onclick="signIn()">Login</button>
<button id="callApiButton" class="hidden" onclick="callApi()">Call Web API</button>
</div>
<pre class="response"></pre>
<script class="pre">
// The current application coordinates were pre-registered in a B2C tenant.
var appConfig = {
b2cScopes: [""]
};
</script>
<script>
"use strict";
// configuration to initialize msal
const msalConfig = {
auth: {
clientId: "e3443e90-18bc-4a23-9982-7fd5e67ff339", //This is your client ID
authority: "https://xyz.b2clogin.com/xyz.onmicrosoft.com/B2c_SignUpSignIn", //This is your tenant info
validateAuthority: false
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
// instantiate MSAL
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
// request to signin - returns an idToken
const loginRequest = {
scopes: appConfig.b2cScopes,
extraQueryParameters: {domain_hint: 'abc'}
};
// request to acquire a token for resource access
const tokenRequest = {
scopes: appConfig.b2cScopes
};
// signin and acquire a token silently with POPUP flow. Fall back in case of failure with silent acquisition to popup
function signIn() {
myMSALObj.loginPopup(loginRequest).then(function (loginResponse) {
getToken(tokenRequest).then(updateUI);
}).catch(function (error) {
logMessage(error);
});
}
//acquire a token silently
function getToken(tokenRequest) {
return myMSALObj.acquireTokenSilent(tokenRequest).catch(function(error) {
console.log("aquire token popup");
// fallback to interaction when silent call fails
return myMSALObj.acquireTokenPopup(tokenrequest).then(function (tokenResponse) {
}).catch(function(error){
logMessage("Failed token acquisition", error);
});
});
}
// updates the UI post login/token acqusition
function updateUI() {
const userName = myMSALObj.getAccount().name;
console.log(myMSALObj.getAccount());
logMessage("User '" + userName + "' logged-in");
// add the logout button
const authButton = document.getElementById('auth');
authButton.innerHTML = 'logout';
authButton.setAttribute('onclick', 'logout();');
// greet the user - specifying login
const label = document.getElementById('label');
label.innerText = "Hello " + userName;
// add the callWebApi button
const callWebApiButton = document.getElementById('callApiButton');
callWebApiButton.setAttribute('class', 'visible');
}
// calls the resource API with the token
function callApi() {
getToken(tokenRequest).then(function(tokenResponse) {
callApiWithAccessToken(tokenResponse.accessToken);
});
}
// helper function to access the resource with the token
function callApiWithAccessToken(accessToken) {
// Call the Web API with the AccessToken
$.ajax({
type: "GET",
url: appConfig.webApi,
headers: {
'Authorization': 'Bearer ' + accessToken,
},
}).done(function (data) {
logMessage("Web APi returned:\n" + JSON.stringify(data));
})
.fail(function (jqXHR, textStatus) {
logMessage("Error calling the Web api:\n" + textStatus);
})
}
// signout the user
function logout() {
// Removes all sessions, need to call AAD endpoint to do full logout
myMSALObj.logout();
}
// debug helper
function logMessage(s) {
document.body.querySelector('.response').appendChild(document.createTextNode('\n' + s));
}
</script>
</body>
</html>
Related
No 'Access-Control-Allow-Origin' header is present on the requested
resource
Failed to load
https://us-central1-social-post-builder-2.cloudfunctions.net/stripe-test-charge: No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3001' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I had just added the cors module to express (on Google Cloud Functions) and it seemed to be a partial fix, because a response object now returns (before, undefined was passed, breaking the page).
Now I get the above error in the console. Page doesn't break. Does my code below not allow all domains?
// https://us-central1-social-post-builder-2.cloudfunctions.net/stripe-test-charge
const app = require("express")();
const stripe = require("stripe")("test_api_key_removed");
const cors = require('cors');
app.use(cors());
app.use(require("body-parser").text());
exports.charge_card = async (req, res) => {
try {
let {status} = await stripe.charges.create({
amount: 2000,
currency: "usd",
description: "An example charge",
source: req.body
});
res.json({status});
} catch (err) {
res.status(500).end();
}
};
The package.json file for the above includes the latest packages as of today.
I don't think the React code needs to be shown, but just in case it is relevant, here is the React component that executes the fetch:
// CheckoutForm.js
import React, {Component} from "react";
import { CardElement, injectStripe } from "react-stripe-elements";
class CheckoutForm extends Component {
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
this.state = {
complete : false
};
}
async submit (event) {
// User clicked submit
let {token} = await this.props.stripe.createToken({name: "Name"});
console.log('CheckoutForm:16, token:', token)
let response = await fetch("https://us-central1-social-post-builder-2.cloudfunctions.net/stripe-test-charge", {
method: "POST",
headers: {"Content-Type": "text/plain"},
body: token.id
});
if (response.ok) console.log("Purchase Complete!")
};
render(props) {
// render variables
if (this.state.complete) return <h1>Purchase Complete</h1>;
return (
<div className='checkout'>
<p>
Would you like to complete the purchase?
</p>
<CardElement />
<button onClick={ this.submit } >
Send
</button>
</div>
);
}
}
export default injectStripe(CheckoutForm);
I have an ionic page with a Facebook login button and a module with a Facebook login controller
the controller is
module.controller('fbLoginCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
// This is the success callback from the login method
var fbLoginSuccess = function(response) {
if (!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.home');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse) {
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function (response) {
console.log(response);
info.resolve(response);
},
function (response) {
console.log(response);
info.reject(response);
}
);
return info.promise;
};
//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function() {
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
console.log('getLoginStatus', success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.home');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
}else{
$state.go('app.home');
}
} else {
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
$ionicLoading.show({
template: 'Logging in...'
});
// Ask the permissions you need. You can learn more about
// FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
})
and my Index page button is
<div class="button-bar" ng-controller="fbLoginCtrl">
<button class="button button-positive icon icon-left ion-social-facebook waves-effect waves-light" ng-click="facebookSignIn()">Facebook</button>
</div>
When i try to run it in the emulator i get this error
Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- fbLoginCtrl
and i don't know how to solve the problem or what is even causing it
please someone help me with this issue
Possibly you are not getting the facebookConnectPlugin plugin. Try running a bower install or npm install before running the emulator.
And if you haven't installed it yet, visit http://ngcordova.com/docs/plugins/facebook/ for the instructions
I just followed the startup tutorial to load up a model.
Firstly I have a exsiting client_id and client_secret from autodesk developer, and then built up a express based application with client_id and client_secret in order retrieve the access token such as
var config ={
credentials: {
client_id: 'xxxxxxxx',
client_secret: 'xxxxxxx',
grant_type: 'client_credentials',
scope:'data:read data:write data:create bucket:create bucket:read'
},
BaseEndPoint: 'https://developer.api.autodesk.com',
Version: 'v1'
} ;
config.AuthenticateEndPoint =config.BaseEndPoint + '/authentication/' + config.Version + '/authenticate' ;
unirest.post (config.AuthenticateEndPoint)
.header ('Accept', 'application/json')
.send (config.credentials)
.end (function (response) {
}
{"access_token":"ruTBP6POxlpcy8HK2KlWzoFu61oE","token_type":"Bearer","expires_in":86399}
This access token is then sent back to a simple html client.
<!DOCTYPE html>
<html>
<head>
<title>Very Basic 3D Viewer</title>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<script src="js/jquery-3.1.1.min.js" ></script>
<!-- The Viewer CSS -->
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/style.min.css" type="text/css">
<link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/A360.css" type="text/css">
</head>
<body>
<div id="viewer"></div>
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/three.min.js?v=v1.2.22"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js?v=v1.2.22"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/Autodesk360App.js"></script>
<!-- Developer JS -->
<script>
$(document).ready(function () {
var viewerApp;
var options = {
env: 'AutodeskProduction',
accessToken: 'YOUR ACCESS TOKEN'
};
var documentId = 'YOUR BASE 64 ENCODED URN';
$.getJSON( 'http://'+window.location.host+ "/gettoken", function( data ) {
console.log(data);
options.accessToken = data.accessToken;
documentId = data.urn;
options.document = data.urn;
});
console.log(options.accessToken, documentId);
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
});
</script>
</body>
</html>
The problem occurred on the client-side, which can successfully get the access token. However this gave me a error
'POST https://developer.api.autodesk.com/utility/v1/settoken 401 (Unauthorized)'
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
i can't figure out what is the problem, something wrong with api or client side or server side?
Note: on registering the developer api, i simply named callback as http://localhost:3000 because currently i am testing it on the local environment, is that the problem ?
The code here
var config ={
credentials: {
client_id: 'xxxxxxxx',
client_secret: 'xxxxxxx',
grant_type: 'client_credentials',
scope:'data:read data:write data:create bucket:create bucket:read'
},
BaseEndPoint: 'https://developer.api.autodesk.com',
Version: 'v1'
} ;
config.AuthenticateEndPoint =config.BaseEndPoint + '/authentication/' + config.Version + '/authenticate' ;
unirest.post (config.AuthenticateEndPoint)
.header ('Accept', 'application/json')
.send (config.credentials)
.end (function (response) {
}
is correct. You get a valid access token, and I assume you run this code from your node.js server. On your server you implement an endpoint, i.e /gettoken, which your client app will call to get the access token returned to your page which initialize the viewer. So far so good.
However, when you consider the calling sequence on your client, there is an issue.
$(document).ready(function () {
means that your code will execute when the DOM is ready - this is fine.
Here, you initialize your variables:
var options = {
env: 'AutodeskProduction',
accessToken: 'YOUR ACCESS TOKEN'
};
var documentId = 'YOUR BASE 64 ENCODED URN';
until here it is still ok, but note that both the accessToken and documentId have invalid valid.
Next, you query the access token using $.getJSON() which is an asynchronous way of calling an endpoint. That means this function returns immediatelly before you read the reply.
So the next code executed is not the one in the callback function, but this one:
console.log(options.accessToken, documentId);
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
at this time, the accessToken and documentId still got invalid values, which will cause your code to fail. In short you need to initialize the Viewer from the callback to wait for the /gettoken response to come back.
$.getJSON( 'http://'+window.location.host+ "/gettoken", function( data ) {
console.log(data);
options.accessToken = data.accessToken;
documentId = data.urn;
options.document = data.urn;
Autodesk.Viewing.Initializer(options, function onInitialized(){
viewerApp = new Autodesk.A360ViewingApplication('viewer');
//viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D);
//viewerApp.loadDocumentWithItemAndObject(documentId);
});
});
Could someone determine how to authenticate myself asynchronously on the Google Drive API using AngularJS and HTML?
I am getting stuck on the call to gapi.auth.authorize because the callback function never gets called:
Here is the AngularJS--HTML5 code excerpt which does not work currently,
var app = angular.module('myApp', []);
app.service('googleService', ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
this.login = function () {
gapi.auth.authorize(
{ client_id: '1009536034660-armd84ckoemm3jan35ceupjhdsmo0fa1.apps.googleusercontent.com', scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' , immediate: true },
this.handleAuthResult);
return deferred.promise;
}
this.handleClientLoad = function {
gapi.client.setApiKey(apiKey);
gapi.auth.init(function () { });
window.setTimeout(checkAuth, 1);
};
this.checkAuth = function () {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true,
hd: domain
}, this.handleAuthResult);
};
this.handleAuthResult = function (authResult) {
if (authResult && !authResult.error) {
var data = {};
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function (resp) {
data.email = resp.email;
deferred.resolve(data);
});
});
} else {
deferred.reject('error');
}
};
this.handleAuthClick = function (event) {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false,
hd: domain
}, this.handleAuthResult);
return false;
};
}]);
app.controller('myController', ['$scope', 'googleService', function ($scope, googleService) {
$scope.login = function () {
$scope.login = function () {
googleService.login().then(function (greeting) {
console.log('Success: ' + greeting);
}, function (reason) {
console.log('Failed: ' + reason);
}, function (update) {
console.log('Got notification: ' + update);
});
};
};
}]);
} else {
deferred.reject('error');
}
};
});
Why is the gapi.auth.authorize failing to call the callback?
First I checked this hypothesis stackoverflow.com/questions/20036893/… and it was incorrect. Next I checked this hypothesis : stackoverflow.com/questions/31659414/… and it was also wrong.
I even tried using Brendan's SetTimeout workaround in this URL, https://groups.google.com/forum/#!topic/google-api-javascript-client/GuFxPzqQ9-0 and it did not function properly.
In addition, I requested and obtained a new OAuth2 client id with the correct javascript origin. Evidently , the onload callback is only called after successful loading of the script. Or, is there a timeout possibility for the callback to be invoked?
Here is Windows 7 ASP.NET program written entirely in Javascript and HTML which works properly :
<html>
<head>
<title>Google+ Sign-in button demo: rendering with JavaScript</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0; width: 600px;}
.hide { display: none;}
.show { display: block;}
</style>
<script src="https://apis.google.com/js/client:platform.js" type="text/javascript"></script>
<script type="text/javascript">
var loginFinished = function (authResult) {
if (authResult) {
console.log(authResult);
}
gapi.client.load('oauth2', 'v2', function () {
gapi.client.oauth2.userinfo.get()
.execute(function (resp) {
// Shows user email
console.log(resp.email);
});
});
};
var options = {
'callback': loginFinished,
'approvalprompt': 'force',
'clientid': '375218714272ao7690jhv6sk7jphi0jf3l5t500sajvt.apps.googleusercontent.com',
'scopes': ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.readonly'],
'requestvisibleactions': 'http://schemas.google.com/CommentActivity http://schemas.google.com/ReviewActivity',
'cookiepolicy': 'single_host_origin'
};
var renderBtn = function () {
gapi.signin.render('renderMe', options);
}
</script>
</head>
<body onload ="renderBtn()">
<div id="renderMe"></div>
</body>
</html>
Could I ask why the Windows 7 ASP.NET Javascript code works okay but not the AngularJS code version?
You have to point $window.location.href at a file in the Windows filesytem which conforms to JavaScript origin naming convention.
My goal is to get $http to work on my local filesystem by caching some static JSON objects in a $cacheFactory. I wish to avoid network requests entirely and use only cached content.
The issue is that $http is making server requests regardless of the existence of cached content. My code is as follows.
Cache Factory
myApp.factory('jsonCache', function($cacheFactory){
// create new cache object
// (tried $cacheFactory.get('$http') as well, but same result)
var cache = $cacheFactory('jsonCache');
// put static value in cache
cache.put('/json/file1.json', {"key":"value"});
return cache;
});
Factory using $http
myApp.factory('AjaxFactory', function($http, jsonCache){
console.log(jsonCache.info()); // {id: 'jsonCache', size: 1}
// this will make a request to "http://localhost/json/file1.json"
// even though there is an entry for that URL in the cache object
$http.get('/json/file1.json', {cache: jsonCache}).success(/* ... */);
return { /* ... */ };
});
At this point I'm thinking it may be the format of the data I'm using in cache.put(), but unsure.
Please see demo code below, commends should help you a bit
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/state1");
//
// Now set up the states
$stateProvider.state('state1', {
url: "/state1",
template: "<h1>State1 </h1> <pre>{{cache | json}}</pre>",
controller: 'state1Ctrl'
})
.state('state2', {
url: "/state2",
template: "<h1>State2 </h1><pre>{{cache | json}}</pre>",
controller: 'state2Ctrl'
});
});
app.controller('state1Ctrl', function($scope, myCache) {
var cache = myCache.cache.get('jsonCache');
//check if cached data exist
if (cache) {
//use cached data
$scope.cache = myCache.cache.get('jsonCache');
//if not update cache
} else {
myCache.update().success(function(data) {
//set cache
myCache.cache.put('jsonCache', data.info);
console.log(myCache.cache.info());
//get cached data
$scope.cache = myCache.cache.get('jsonCache');
}).error(function() {
console.log("error");
});
}
});
app.controller('state2Ctrl', function($scope, myCache) {
var cache = myCache.cache.get('jsonCache');
if (cache) {
$scope.cache = myCache.cache.get('jsonCache');
} else {
myCache.update().success(function(data) {
myCache.cache.put('jsonCache', data.info);
console.log(myCache.cache.info());
$scope.cache = myCache.cache.get('jsonCache');
}).error(function() {
console.log("error");
});
}
});
app.factory('myCache', function($cacheFactory, $http) {
// create new cache object
var cache = $cacheFactory('jsonCache');
// put static value in cache
function update() {
alert("update")
return $http.get("https://ws.spotify.com/search/1/track.json?q=kaizers+orchestra");
}
return {
cache: cache,
update: update
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<body ng-app="app">
<div ui-view></div>
<!-- We'll also add some navigation: -->
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</body>
I was actually able to get it working as desired on this plunk http://plnkr.co/edit/x1nfjwEoJOxzZN5PUyrX?p=preview
angular.module("myApp", [])
.factory('jsonCache', function($cacheFactory) {
// create new cache object
// (tried $cacheFactory.get('$http') as well, but same result)
var cache = $cacheFactory('jsonCache');
// put static value in cache
cache.put('file1.json', {
"key": "From Cache Factory"
});
return cache;
})
.factory('jsonFactory', function($http, jsonCache) {
var get = function(url) {
return $http.get(url, {
cache: jsonCache
});
};
return {
get: get
};
})
.controller("Ctrl", function($scope, jsonFactory, jsonCache) {
$scope.cacheInfo = jsonCache.info();
jsonFactory.get('file1.json').success(function(res) {
$scope.json = res;
});
});
I think the issue with my original code was the result of one of the many 3rd party module dependencies. (doh!)
My workaround for the code as it was, was the following:
myApp.factory('jsonFactory', function($http, $q, jsonCache){
var get = function(url){
var data = jsonCache.get(url);
// if data exists in cache, wrap in promise and return
// or do regular $http get
if(data){
return $q(function(resolve, reject){ resolve(data); });
} else {
return $http.get(url);
}
};
return {
get: get
};
});