简体   繁体   中英

AngularJS wrapping JSON data returned from server

I have a basic CRUD application up and running, however what I am wanting to do is wrap every response from the server with two additonal parameters namely

'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}

so that I can handle when a successful request is sent and returned from the server, however the database was unable to update for some reason so I can not only keep the UI in sync with the DB, but also present the user an error message on a failed update. As AngularJS expects an updated object the UI will be in sync if I return the same object on failure, but as there would be no notification of failure the user wouldn't realize what the problem is.

Within my old applications pre-Angular (jQuery based) I could easily decode the json data on every response and if error === true present an error message, but in Angular I cannot seem to figure out how to accomplish this.

I may very well be off base here as I am just getting into Angular so any direction would be helpful.

Make this http request from angularjs and send back a response object from server.

response object --->{'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}}

which gets collected in Resdata. use Resdata to take action.

 $http({method: 'POST', url:url, data:body}).success(function(Resdata, status, headers,   config) {
        console.log(Resdata);

        if(Resdata.error == true){
            // use Resdata.errorMessage
        }
        else if(Resdata.error == false){
           // use Resdata.data
        }
    }).error(function(Resdata, status, headers, config) {
        console.log("error:", error);
    });

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