0

I am new to Angular and trying to retrieve a custom error from a promise object in Angular JS. But i am not getting back the custom error on my html. What am i doing wrong?

Here is my HTML file -

<!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>

Here is my script file(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"
        });        
    
  })}());

I need the error to be rendered back to my html when i alter the url(api info) to a incorrect url address.

6
  • 2
    Did you mean catch instead of the second then? ;-) Commented Dec 28, 2018 at 18:29
  • yes. But i tried to do the same by chaining two "then". I performed chaining by looking into this - stackoverflow.com/questions/23559341/… Commented Dec 28, 2018 at 18:31
  • 2
    The link you refer to has the then - catch sequence in the accepted answer (the promisified version). Why do you expect that a second then would get the error info? then is for fulfilment, catch for rejection. You can chain then, but that is not for treating rejections. Commented Dec 28, 2018 at 18:35
  • @trincot that makes sense. So, how do i correct my code with the usage of catch? Commented Dec 28, 2018 at 18:37
  • 2
    Literally replace the second .then with .catch Commented Dec 28, 2018 at 18:38

1 Answer 1

1

here goes the answer after suggestions from peers -

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

  })}());

Solution - Replace 2nd 'then' with 'catch'.

Sign up to request clarification or add additional context in comments.

Comments