简体   繁体   中英

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM