Kgn-web
Kgn-web

Reputation: 7555

how to call a function on page load in angular service

Below is how my angular app looks like.

(function () {
  "use strict";

angular
    .module("app.core", ['ngRoute']);

}());

Service

(function () {

'use strict';

angular
    .module('app.service')
    .factory('dataService', dataService);

dataService.$inject = ['$http', '$q'];

function dataService($http, $q) {

    var service = {
        create: create,
        read: read,
        update: update,
        remove: remove
    }

    return service;

    function read() {
        return
        $http.get("APIURL")
        .then(success)
        .catch(exception);

        function success(response) {

        }

        function exception(ex) {

        }

    }

  function create() {} 
  function update() {}
  function detete() {}

 }
})`

index.html

  <body ng-app="app.core">
     <div ng-view> </div>
  </div>

On page load, home-template.html is inserted into ng-view.

No clue on below

what would be the right way to call only dataService's read() on page load?

Upvotes: 0

Views: 1843

Answers (1)

Mike Feltman
Mike Feltman

Reputation: 5176

The normal use case is to call the service in the constructor of your controller.

John Papa's style guide has a lot of detailed guidance on this type of architecture and best practices. I'd highly recommend it.

https://github.com/johnpapa/angular-styleguide/tree/master/a1

Upvotes: 1

Related Questions