Changing urlBase at runtime in Angular lb-services.js

302 views
Skip to first unread message

Chregan O'Flynn

unread,
Oct 3, 2014, 3:21:23 AM10/3/14
to loopb...@googlegroups.com
Hey

I need to be able to edit the API url (urlBase) in lb-services.js at runtime (if there is a connection drop, the app will search for a server on the local network with a clone of the Loopback API running)

I thought of creating a service that holds the config data, but then how would I apply that to the LB service without having to edit lb-services.js (This would be a laborious task and I would need to re-do it every time I generated the lb-services file)

Any help would be greatly appreciated.

thanks very much

take care
Chregan


Miroslav Bajtoš

unread,
Oct 3, 2014, 1:27:45 PM10/3/14
to loopb...@googlegroups.com
On Friday, October 3, 2014 9:21:23 AM UTC+2, Chregan O'Flynn wrote:
Hey

I need to be able to edit the API url (urlBase) in lb-services.js at runtime (if there is a connection drop, the app will search for a server on the local network with a clone of the Loopback API running)

A pull request was landed recently that added support for setting a custom API url at the client side - see https://github.com/strongloop/loopback-sdk-angular/pull/81.

However, the solution changes the URL at the configuration time, i.e. you have to create a new injector and recreate all your services if you want to change the URL at runtime.

Miroslav

Chregan O'Flynn

unread,
Oct 4, 2014, 6:27:10 AM10/4/14
to loopb...@googlegroups.com
Thanks very much for that Miroslav!

It looks like a great start to what I need to do. thanks

Chregan O'Flynn

unread,
Nov 20, 2015, 4:46:32 PM11/20/15
to loopb...@googlegroups.com
Hey

I am just posting this here in case anyone else had the same issue. I am not sure if this is best practice but it works for me :)

I create a provider that looks for a variable stored in localStorage. then inject that value into the config function
.provider('apiURLFetcher', function(){
        if(!localStorage.getItem('apiURL')){ // if there is no apiURL in localStorage, set a default value
            localStorage.setItem('apiURL', "https://xxxxxxxxxxxxx/api")
        }
        this.getURL = function(){ // fetches apiURL from localStorage
            return JSON.parse(localStorage.getItem('apiURL'));
        };
        this.$get = function(){
            return JSON.parse(localStorage.getItem('apiURL'));
        }
    })
    .config(function (apiURLFetcherProvider, ImgCacheProvider,$stateProvider, $urlRouterProvider, $httpProvider, LoopBackResourceProvider) {
        LoopBackResourceProvider.setUrlBase(apiURLFetcherProvider.getURL());
        .........

Then I can change this localStorage variable elsewhere in my app, and the next time the app starts, it will initialise loopback services with the new url base.

take care
Chregan
Reply all
Reply to author
Forward
0 new messages