programing

$http 오류입니다.get in angularJS -- 함수가 아닌 성공

instargram 2023. 3. 3. 16:50
반응형

$http 오류입니다.get in angularJS -- 함수가 아닌 성공

다음 오류 발생:

angular.min.js:122 TypeError:$http.get(...).성공은 객체의 신규(app.js:12)에서 getUserInfo(app.js:7)에서 함수가 아닙니다.Q.instance(angular.min.js:93)에서 p(angular.min.js:68)에서 g(angular.min.js:61)에서 g(angular.min.js:61)에서 g(angular.min.js:61)를 호출한다.

코드는 다음과 같습니다.

var gitHub = angular.module('gitHub', []);

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    var $scope.user = '';
    function getUserInfo($scope, $http){ 
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    getUserInfo($scope, $http);
}]);

여기 html이 있습니다.

<!DOCTYPE html>
<html ng-app="gitHub">
<head>
    <title>Github Users Directory</title>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <div ng-controller="mainController">
        <div>
            <h1>GitHub Users</h1>
            Who do you want to search for?<input type="text" name="FindHim" ng-model="queryName" />
            <button ng-click="getUserInfo()">Search</button>
        </div>
        <div>
            {{ user }}
        </div>

    </div>
</body>
</html>

.success그리고..error방법은 권장되지 않으며 AngularJS 1.6에서 제거되었습니다. 표준 사용.then대신 메서드를 사용합니다.

$http.get('https://api.github.com/users')
  .then(function (response) {

    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;

    $scope.user = data;
    console.log(data);
});

폐지 통지

$http레거시 약속 방식.success그리고..error는 더 이상 사용되지 않으며 v1.6.0에서 삭제됩니다.표준 사용.then대신 메서드를 사용합니다.

- AngularJS (v1.5) $http Service API Reference -- 폐지 알림.

또한 SO: 각 $http 성공/오류 메서드가 권장되지 않는 이유는 무엇입니까?

앵글을 사용할 때는 .success가 아니라 .success를 사용해야 한다고 생각합니다.

문서의 예

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

다음은 $Http의 사용 예를 제시하겠습니다.

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

그리고 마지막으로 당신의 코드는 이렇게 될 수 있습니다.

$scope.getUserInfo = function () {
    $http.get('https://api.github.com/users')
        .then(function (result) {
            $scope.user = result;
            console.log(result);
        }, function(result) {
            //some error
            console.log(result);
        });
};

이것은 효과가 있다

https://docs.angularjs.org/api/ng/service/$http

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

현재 구현에서는 인수를 전달하고 있지 않습니다(즉,$scope그리고.$http)에 대해서getUserInfo부터ng-click="getUserInfo()"에러가 발생하고 있습니다.

이것들을 인수로 넘길 필요는 없습니다.$scope그리고.$http컨트롤러에 이미 삽입되어 있기 때문에 기능을 정의합니다.$scope.

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    $scope.user = '';
    //Redefined function, without arguments
    $scope.getUserInfo = function (){ 
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    $scope.getUserInfo();
}]);

$scope, $http를 투입할 필요가 없습니다.

app.controller('MainController', function($scope, $http) { 
  $scope.fetchData = function(_city){
    $http.get("../api/AllPlaces?filter[where][placeCity]="+ _city)
    .then(function(response) {
      $scope.Data = response.data;
    });
  }
});

컨트롤러에 의존관계로서 $http를 이미 삽입했기 때문에 함수 파라미터로서 $http를 전달할 필요는 없습니다.코드를 조금 수정했습니다.잘 되는지 확인 부탁드립니다.

var gitHub = angular.module('gitHub', []);

gitHub.controller('mainController', ['$scope', '$http', function ($scope, $http) {

    $scope.user = '';

    $scope.getUserInfo = function() {
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    $scope.getUserInfo();
}]);

각도 JS에 따라$http 매뉴얼, 이 시스템은 에서 제외되었습니다.1.4.3 +그래서 내가 그의 포스트에서 도움을 받았으니 너는 이렇게 해봐.

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (success){

   },function (error){

   });
}

또는

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

나는 나에게 더 유연한 두 번째 것을 선호한다.

$http({
    method: 'GET',
    url: '....',
    headers: {
        'Authorization': 'Bearer ' + localStorage["token"]
    }
})
.then(function (data, status, headers, config) {
     alert(JSON.stringify(data) + "Status" + status);
})
.error(function (data, status, headers, config) {
     alert(JSON.stringify(data) + "Status" + status);
});
function successCallback(response) {
return response
}
$http.get('url')
.then(successCallback)

언급URL : https://stackoverflow.com/questions/41183845/error-with-http-get-in-angularjs-success-not-a-function

반응형