2016-09-29 52 views
0

你好,我是新的JavaScript和AngularJS.This是我的功能从服务器获取上传.json(服务器返回一个JSON):如何从URL状态代码

function getProducts() { 
     return $http.get(urlProducts).then(
      //Success 
      function(response) { 
       products= response.data.result; 
       return products; 
      }, 
      //Error 
      function(response) { 
       //put best way to return an error 
       return something; 
      } 
     ); 
    } 

我的问题是:这是从Web服务器 我想知道获取数据的最佳方式并非只有成功了的响应,也如果状态代码是200

然后,我想知道,如果是错误我真的想要返回(我想用文本显示图像:“不可以连接服务器,再试一次”)。但我使用Ionic(HTML5,CSS3和JavaScript与AngularJS)制作应用程序。所以...什么是最好的方式来返回一个错误,我想用一段文字来展示一个图像,这个错误是关于我在apache cordova中编程的。 谢谢!

+2

http://stackoverflow.com/questions/27507678/in-angular-http-service-how-can-i-catch-the-status-of-error – epascarello

+1

你不应该担心状态码200,如果状态代码不是200个代码中的一个,承诺将被'$ http'拒绝 – charlietfl

回答

0

作为每AngularJS文档:

的$ HTTP服务是核心角服务便于与远程HTTP服务器

从$ HTTP调用的响应对象具有这些 通信属性(除其他外):

数据 - {string | Object} - 使用转换函数转换的响应正文。

status - {number} - 响应的HTTP状态码。您可以使用它来根据不同代码制定逻辑

statusText - {string} - 响应的HTTP状态文本。

在你的例子中,你已经实现了Promise.protorype.then()函数,它允许你委托成功(第一个参数)和错误(第二个参数)进行进一步处理,一旦承诺完成($ http。拨打电话已完成)。

这是我将如何根据您的例子做:

function getProducts() { 
    // Call the http get function 
    return $http.get(url).then(

     //The request succeeded - 200 status code 
     function(response) { 
      products= response.data.result; 
       return products; 
     }, 

     //The request failed 
     function(response) { 

      // Here you can access the status property and the statusText 
      console.log("Http Status: " + response.status + " Description: " + response.statusText); 

      // Return a false result 
      return false; 
}); 

我通常会使用一个库像Angular-UI-Notification,并清理了一下我实现它是这样的:

//The success handler function 
function handle_response_success(response) { 
    // Do processing here based on the response then show a success notification 
    Notification.success('Success notification'); 
}; 

// The error handler function 
function handle_response_error(error) { 
    Notification.error('Something went wrong with that request. More Info: ' + 'Http Status: ' + error.status + ' Description: ' + error.statusText); 
} 

// Then finally bind it to your getProducts call 

function getProducts() { 

    // More elegant proto imho 
    return $http({ method: 'GET', 
     url: 'http://example.com' 
    }); 
}; 

// More elegant way to handle this imho 
getProducts.then(handle_response_success.bind(this), handle_response_error.bind(this); 
+0

感谢您的回复。如何在视图中显示错误图像? –

+0

有很多方法可以实现这一点。最简单的方法是将消息绑定到$ scope属性,然后用ng-model显示。如果您还需要进一步的帮助,请提出另一个问题,我会很乐意回答。如果他们帮忙,也请提高答案 – geekonedge