Emad Dehnavi
Emad Dehnavi

Reputation: 3441

Best practice to get a json response object in angularjs

I have an API which return a json array object, right now, I get the json in my Controller like this and it works just fine :

angular.module('lyricsApp', [])
.controller('LyricsController', ['$scope', 'ApiCall', function ($scope, ApiCall) {
    $scope.lyrics = {
        id: "",
        songName: "",
        singerName: "",
        writtenBy: "",
        lyricText: "",
        isEnable: "",
        created_at: "",
        updated_at: ""
    };

    $scope.searchLyric = function () {
        var result = ApiCall.GetApiCall().success(function (lyrics) {
            $scope.lyrics.id = lyrics.data.id
            $scope.lyrics.singerName = lyrics.data.singerName;
            $scope.lyrics.songName = lyrics.data.songName;
            $scope.lyrics.writtenBy = lyrics.data.writtenBy;
            $scope.lyrics.lyricText = lyrics.data.lyricText;
            $scope.lyrics.isEnable = lyrics.data.isEnable;
            $scope.lyrics.created_at = lyrics.data.created_at;
            $scope.lyrics.updated_at = lyrics.data.updated_at;   
        });
    }
}])

But I think this is not a good practice, I already try this :

var result = ApiCall.GetApiCall().success(function (lyrics) {
     $scope.lyrics=lyrics.data;
});

in this case I get undefined value :

console.log($scope.lyrics.id); // show Undefined

So, if you guys can suggest a better way I will be appreciate it.

Upvotes: 1

Views: 962

Answers (1)

Vivek V Dwivedi
Vivek V Dwivedi

Reputation: 2615

You are doing the right thing, except for console.log. If your log statement is executed before the assignment is done, you will get the undefined value.

Also I don't see why you would do a var result =

You can simply do

ApiCall.GetApiCall('v1', 'lyrics', '1').success(function (data) {
    $scope.lyrics = data.data;
    console.log($scope.lyrics.id);
}).error(fucntion(data){
    console.log(data);
});

Upvotes: 3

Related Questions