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.

Alireza
  • 2,319
  • 2
  • 23
  • 35
  • 2
    Did you mean `catch` instead of the second `then`? ;-) – trincot Dec 28 '18 at 18:29
  • yes. But i tried to do the same by chaining two "then". I performed chaining by looking into this - https://stackoverflow.com/questions/23559341/using-success-error-finally-catch-with-promises-in-angularjs –  Dec 28 '18 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. – trincot Dec 28 '18 at 18:35
  • @trincot that makes sense. So, how do i correct my code with the usage of catch? –  Dec 28 '18 at 18:37
  • 2
    Literally replace the second `.then` with `.catch` – Patrick Roberts Dec 28 '18 at 18:38
  • @PatrickRoberts That solved my issue. Thank you very much. –  Dec 28 '18 at 18:40

1 Answers1

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'.