问题描述
我从angularJS开始,我尝试通过服务发出HTTP get请求。 这部分正在工作,我将数据放入一个名为text_resp的响应变量中。 我只想在单击按钮时发出此API请求,所以我将它与刷新方法上的控制器链接起来。 我无法在控制器中访问text_resp,您知道为什么吗? 这是代码:
var myApp = angular.module('myApp',[])
//define a service named monService
myApp.service('monService',function ($http) {
this.ingredients = 'pomme';
this.add = function (Ingredient) {
this.ingredients = this.ingredients + ',' + Ingredient;
return this.ingredients;
};
this.text_resp = '';
this.request = function() {
var request_obj = $http({
method: 'GET',url: 'https://world.openfoodfacts.org/cgi/search.pl?search_terms=banania&search_simple=1&action=process&json=1'
}).then(
function successCallback(response) {
console.log("success")
this.text_resp = response.data;
console.log("1")
console.log(this.text_resp);
},function errorCallback(response) {
console.log("error")
this.text_resp = "error server";
});
console.log("async");
console.log(this.text_resp)
}
console.log("2")
console.log(this.text_resp)
});
myApp.controller('Controller',function($scope,monService) {
$scope.mesIngredients = monService.add('carotte');
$scope.mareponse = monService.text_resp;
$scope.refresh = function(){
monService.request();
console.log($scope.mareponse)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)