微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在控制器中获取服务变量

如何解决在控制器中获取服务变量

我从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 举报,一经查实,本站将立刻删除。