Search code examples
javascriptangularjsapiionic-frameworksplash-screen

ionic hide splashscreen after api call are completed


I want to keep the Splashscreen displayed until my application end-up to fetch multiple data from different Api call. The code to hide the Splashscreen is based on a Timer and I don't want that:

 app.run(function($cordovaSplashscreen) {
    setTimeout(function() {
    $cordovaSplashscreen.hide()
  }, 5000)
 })

The current behaviour that I have it's a Splashscreen displaying for 5 seconds and then come's up the first view in a blank page, only after few seconds, the data will be visible in my view.

My question is: How can I add the logic in my app.js to hide the Splashscreen only when the API call are done, so that way the user will see the first view with all the data ready to use.


Solution

  • What you can do is waiting for all requests to be finished with $q.all(promises) using angularjs built-in promise library. Within the success function you can call $cordovaSplashscreen.hide() in your controller to hide the splashscreen like user46772 already mentioned. Example code:

    index.html

    <body ng-controller="AppController"></body>
    

    app.js

    var module = angular.module( "app", [ "ngCordova", "yourServices" ] )
    
    module.config( ... );
    module.run( ... );
    module.controller( "ApplicationController", ApplicationController );
    
    function ApplicationController( $cordovaSplashscreen, $q, apiCallService ) {
    
        loadData();
    
        function loadData() {
    
            $q.all( apiCallService.loadFoo1, apiCallService.loadFoo2, apiCallService.loadFoo3)
                 .then( onSuccess, onError );
    
            function onSuccess() {
                $cordovaSplashscreen.hide()
            }
    
            function onError() {
                // do something useful else
            }
        }
    }
    

    yourServices.js

    angular
        .module( "yourServices", [ "$http" ] )
        .factory( "apiCallService", apiCallService );
    
    function apiCallService( "$http" ) {
        return {
            loadFoo1: loadFoo1,
            loadFoo2: loadFoo2,
            loadFoo3: loadFoo3
        }
    
        function loadFoo1() {
            return $http.get( "yourAPI" );
        }
    
        ...
    }
    

    Be aware that this code is not a working example. But it should explain how you could proceed to solve your issue. Furthmore you have to think about what should happen if one of your requests fails at the onError() function.

    Additionally you should wrap the code into the onDeviceReady event. Assuming you are using ionic you can make use of this piece of code:

    $ionicPlatform.ready( loadData );
    

    Do not forget to inject the $ionicPlatform into the controller function.