Всякий раз, когда мне нужно быстро извлечь что-то из HTML-документа, я использую Tidy, чтобы преобразовать его в XML, а затем использовать XPath или XSLT, чтобы получить то, что мне нужно. В вашем случае что-то вроде этого:
//p/a[@href='foo']
Методы .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
устарели и будут удаляться в версии 1.6.0. Вместо этого используйте стандартный метод.then
.- AngularJS (v1.5) $ HTTP API API-службы - уведомление об изъятии .
blockquote>Также см. SO: Почему угловые $ http-методы успеха / ошибки устарели? .
это работает
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.
});
Я думаю, вам нужно использовать. then и not .success при использовании углового .
Пример из документа doc
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);
});
};
.then()
, хотя они должны, поскольку .success()
устарели. Вероятно, вы должны привести пример, который использует $http
с .then()
, а не общий пример обещания.
– Duncan
16 December 2016 в 13:12
Согласно документации Angular 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 в качестве параметра функции, так как вы уже ввели $ 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();
}]);
$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);
});
В соответствии с вашей текущей реализацией вы не передаете аргументы (т.е. $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;
}); } });
function successCallback(response) {
return response
}
$http.get('url')
.then(successCallback)