Pages

Wednesday, July 12, 2017

AngularJS service with var declarations instead of this. assignments

So I spent a couple of hours trying to figure out why a generally very good Angular sample I thought I'd implemented correctly wouldn't work. Specifically, the service had this code:

sulhome.kanbanBoardApp.service('boardService', function ($http, $q, $rootScope) {

    var getColumns = function () {
        return $http.get("/api/BoardWebApi").then(function (response) {
            return response.data;
        }, function (error) {
            return $q.reject(error.data.Message);
        });
    };

which was called this way in the controller.

sulhome.kanbanBoardApp.controller('boardCtrl', function ($scope, boardService) {
    boardService.getColumns();

The problem is, this doesn't work. The proper way to set a function in a service should look like this:

sulhome.kanbanBoardApp.service('boardService', function ($http, $q, $rootScope) {

    this.getColumns = function () {
        return $http.get("/api/BoardWebApi").then(function (response) {
            return response.data;
        }, function (error) {
            return $q.reject(error.data.Message);
        });
    };

See the difference? this.getColumns, not var getColumns.

So, how was this other guy's code working? It was--I downloaded and ran his sample.

A service is a function with nested functions. He returned the functions in the parent function, like so:

sulhome.kanbanBoardApp.service('boardService', function ($http, $q, $rootScope) {

    var getColumns = function () {
        return $http.get("/api/BoardWebApi").then(function (response) {
            return response.data;
        }, function (error) {
            return $q.reject(error.data.Message);
        });
    };

    return {
            getColumns: getColumns
        };

So far, I haven't seen any other samples do it this way. It works, but...why the extra code step?

No comments:

Post a Comment