【问题标题】:promise object not rendering error in Angular JS [duplicate]Angular JS中的promise对象不呈现错误[重复]
【发布时间】:2019-05-26 12:47:06
【问题描述】:

我是 Angular 的新手,并试图从 Angular JS 中的 promise 对象中检索自定义错误。但我没有在我的 html 上找回自定义错误。我做错了什么?

这是我的 HTML 文件 -

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script data-require="angular.js@*" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
  <script data-require="angular.js@*" data-semver="4.0.0" src="script.ts"></script>
  <script data-require="angular.js@*" data-semver="4.0.0" src="system.config.js"></script>
  <script data-require="angular.js@*" data-semver="4.0.0" src="tsconfig.json"></script>
  <script src="script.js"></script>
</head>

<body>
  <div ng-controller="myCtrl">
    <div>{{message}}</div>
    <div>{{error}}</div>
    <div>Name: {{user.name}}</div>
    <div>Location: {{user.location}}</div>
    <div>
      <img ng-src="{{user.avatar_url}}" title="{{user.name}}">
    </div>
  </div>
</body>

这是我的脚本文件(script.js) -

(function(){
  angular.module('myApp', []).controller('myCtrl', function($scope, $http) {
    $http.get("https://api.github.com/users/rohitj559")
        .then(function(response){
          $scope.user = response.data;
        })
        .then(function(reason){
          $scope.error = "Could not fetch the user"
        });        
    
  })}());

当我将 url(api 信息)更改为不正确的 url 地址时,我需要将错误呈现回我的 html。

【问题讨论】:

  • 您的意思是catch 而不是第二个then? ;-)
  • 是的。但我试图通过链接两个“then”来做同样的事情。我通过查看这个来执行链接 - stackoverflow.com/questions/23559341/…
  • 您引用的链接在接受的答案(承诺版本)中有then - catch 序列。为什么你期望第二个then 会得到错误信息? then 用于履行,catch 用于拒绝。你可以链接then,但这不是用来处理拒绝的。
  • @trincot 说得通。那么,如何使用 catch 更正我的代码?
  • 将第二个 .then 替换为 .catch

标签: javascript html angularjs promise


【解决方案1】:

根据同行的建议,这里是答案 -

(function(){
  angular.module('myApp', []).controller('myCtrl', function($scope, $http) {
    $http.get("https://api.github.com/users/rohitj559")
        .then(function(response){
          $scope.user = response.data;
        })
        .catch(function(reason){
          $scope.error = "Could not fetch the user"
        });        

  })}());

解决方案 - 将第二个 'then' 替换为 'catch'。

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多