I want to define a simple factory that will be the entry point for a $resource
definition for a given resource in my app (say Post
). The problem is that the URL for Post
depends on the user's organization, so it doesn't make sense (nor is it even possible) to instantiate the Post
class until the user has signed in (eg, a url like https://host.com/organizations/your-org/posts/:id
)
The controllers that depend on Post
are all protected by login and so it should be OK (in theory) to define Post
assuming the user has already logged in.
However I've found that simple requiring Post
in any controller signature initializes the Post
factory at bootstrap time.
angular.module('myapp.services', [])
.factory("Post", function($resource, Auth, $localStorage){
return $resource(Auth.links.posts.href, {id: "@id"});
});
Auth.links
is initialized after login, so bootstrapping the app when a user is logged out causes errors because Auth.links
is null.
I've thought of 2 ways to deal with this, neither of which I'm really excited about:
- Rewrite
Post
factory to return a promise that will be immediately resolved assuming you're logged in. But why create another callback when this should just work? - Make the initial
Post
factory a stub and then modify theAuth.login()
method so that it overwrites thePost
factory with the correct definition. This seems hacky and non-standard, and I've read that trying to add services or factories after the app has been bootstrapped doesn't work properly (without some hacks).
Has anyone solved similar problems before? And/or do you recommend some particular approach? Thanks in advance.
EDIT:
SOOOO apparently I had an if
statement incorrect in my router that was defaulting logged-out users to a logged-in page, which was causing this whole mess.
Turns out that stuff does actually work how it's supposed to and my problem was coder error. Derp.