简体   繁体   English

AngularJS包装从服务器返回的JSON数据

[英]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 我已经启动并运行了一个基本的CRUD应用程序,但是我想要做的是用两个附加参数包装来自服务器的每个响应:

'error' => boolean, 'errorMessage' => string, 'data' => {whatever data} '错误'=>布尔值,'errorMessage'=>字符串,'数据'=> {任何数据}

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. 这样我就可以处理从服务器发送和返回成功请求的时间,但是由于某种原因数据库无法更新,因此我不仅可以使UI与DB保持同步,还可以向用户显示一条错误消息更新失败。 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. 正如AngularJS期望的是更新的对象一样,如果我在失败时返回相同的对象,UI将是同步的,但是由于不会有失败的通知,因此用户不会意识到问题所在。

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. 在我的旧应用程序(在基于Angular的旧版(基于jQuery)中)中,我可以轻松解码每个响应上的json数据,如果error === true则显示错误消息,但是在Angular中,我似乎无法弄清楚该如何实现。

I may very well be off base here as I am just getting into Angular so any direction would be helpful. 我可能刚在这里落脚,因为我刚进入Angular,所以任何方向都将对您有所帮助。

Make this http request from angularjs and send back a response object from server. 从angularjs发出此http请求,然后从服务器发送回响应对象。

response object --->{'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}} 响应对象---> {'error'=>布尔值,'errorMessage'=>字符串,'data'=> {任何数据}}

which gets collected in Resdata. 收集在Resdata中。 use Resdata to take action. 使用Resdata采取行动。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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