简体   繁体   中英

Use multiple service in same controller angular js

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM