0

I want to use multiple service in same controller. I can achieve with different service as mentioned below but it performs only one service

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<H1>Random Text is:</H1>

<div>{{myRandom}}</div>

<p>MuyLocation:: {{myLocation}}.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $location) {
  $http.get("http://www.randomtext.me/api/").then(function (response) {
      $scope.myRandom = response.data.text_out;
      $scope.myLocation= $location.absUrl();
  });
});
</script>

</body>
</html>

BUT, i want to use both service in same controller as mentioned below

app.controller('myCtrl', function($scope, $http, $location) {

  $http.get("welcome.htm").then(function (response) {
      $scope.myWelcome = response.data;
      $scope.myUrl = $location.absUrl();
  });
});

So How can we perform both services in same controller.

Thanks in advance.

6
  • You have already solved your own problem and answered your question. The last snippet is the answer and it will work correctly Commented Aug 16, 2016 at 6:47
  • Have you got an error message ? I agree with Umair, your last snippet must works. But if you minified js, try to declare your controller with array like this : app.controller('myCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) { .. }]); In some case minification can cause issue with DI Commented Aug 16, 2016 at 6:53
  • I have tried to edit with w3schools.com/angular/tryit.asp?filename=try_ng_services_http but it not works. Commented Aug 16, 2016 at 6:59
  • What does not work? Commented Aug 16, 2016 at 7:01
  • @Silvinus, please check my updated question... Commented Aug 16, 2016 at 7:10

1 Answer 1

1

I think you can solved your problem with promise chaining.

$http.get("http://www.randomtext.me/api/").then(function success(response) { 
 return $q.resolve(response);
 }, function error() {
 return $http.get("welcome.htm");
}).then(function success(response) { 
  $scope.myWelcome = response.data;
  $scope.myUrl = $location.absUrl();
});

If call to randomapi failed, so fetch welcome.html.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.