gpt4 book ai didi

javascript - $http 服务未触发 Controller angularjs 中的成功处理程序?

转载 作者:行者123 更新时间:2023-11-28 15:16:05 25 4
gpt4 key购买 nike

我正在开发 AngularJS 应用程序。在最初构建基本应用程序后,我已转向以 Angular 进行路由。我已经成功实现了路由。我之前页面中的数据到达我正在使用 $routeParams 进行路由的页面。

在我的 Controller 内,我使用从 $routeParams 服务接收的输入来调用 $http 服务。我使用所有 REST API,并且在 chrome 的网络选项卡中看到响应返回,但未调用 http 服务的成功处理程序。尝试调试但从未达到断点。

这是我的路由配置:

var app = angular.module('mainApp',['ngRoute']); 
app.config(function($routeProvider){
$routeProvider.when('/',{
templateUrl:"main.html",
controller:'CategoriesController'
}).when('/imagedetails/:imageId',{
templateUrl: 'imagedetails.html',
controller:'ImageDetailsController'
})
.otherwise({redirectTo:'/'});

});

因此,我将 imageId 传递给 ImageDetailsController 以从 REST API 获取数据。

这是我的 Controller :

 var ImageDetailsController = function($scope, $http, $routeParams)
{
$scope.imageId = $routeParams.imageId;
console.log("Print image id : " + $scope.imageId);
$scope.image = {};
$scope.params = $routeParams;

var downloadImageRequest = {
method: 'GET',
url: '<my-rest-api-url>',
headers: {
'Content-Type': 'application/json'
}
};

$http(downloadImageRequest).then(onImageSuccess, onImageFailure);

var onImageSuccess = function(response){ // i have put debug inside this method but never reaches controller
console.log(response );
$scope.image = response.data.results[0];
};
var onImageFailure = function(response){
alert("Failed to load image please try again!!");
console.log(response);
};
}

在 Chrome 开发者工具的“网络”选项卡中,响应是可见的,但上面的方法中我设置的响应未触发。

请帮忙

最佳答案

您应该首先定义变量,然后使用它们。定义变量与定义函数不同。所以你可以:

    var onImageSuccess = function(response){
console.log(response );
$scope.image = response.data.results[0];
};

var onImageFailure = function(response){
alert("Failed to load image please try again!!");
console.log(response);
};

$http(downloadImageRequest).then(onImageSuccess, onImageFailure);

或者你可以定义一个命名函数:

    $http(downloadImageRequest).then(onImageSuccess, onImageFailure);

function onImageSuccess(response){ // i have put debug inside this method but never reaches controller
console.log(response );
$scope.image = response.data.results[0];
}

function onImageFailure(response){
alert("Failed to load image please try again!!");
console.log(response);
}

关于javascript - $http 服务未触发 Controller angularjs 中的成功处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33889119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com