AngularJS-无法使用工厂调用http服务 [英] AngularJS - Unable to call http serrvice using factory

查看:103
本文介绍了AngularJS-无法使用工厂调用http服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为解决我的问题,我在不同站点上浏览了许多文章,但没有一篇文章解决. 我正在编写一个简单的AngularJS应用程序.我对Angular很陌生.我已经编写了一个工厂方法,该方法调用$ http服务,该服务从Web api获取数据. Web api运行良好,并且按预期返回了JSON对象.

To resolve my issue I have gone through many articles on different sites, but none resolved it. I'm writing a simple AngularJS application. I'm quite new to Angular. I have written a factory method which call the $http service which gets the data from the web api. Web api is running fine and its returning the JSON object as expected.

角度代码

 var app = angular.module("app", [])
            .controller("controller", function ($scope, WebFactory) {
                $scope.data = "data";
                $scope.error = "error";
                $scope.data=WebFactory.getData();

            })
            .factory("WebFactory", function ($http) {
                var obj = {};

                obj.getData = function()
                {
                    $http({
                        method: "GET",
                        url: "http://localhost:37103/api/employee",                      
                    }).then(function success(response) {
                        return response.data;
                    })
                    .then(function error(response) {
                        return response;
                    });
                    return 'No data';
                }
                return obj;

            });

HTML代码

 <body ng-controller="controller">

data: {{data}}
<br/>
error: {{error}}
<br />

我已经花了2天的时间,但仍然不知道为什么它不起作用.

I have spent 2 days, but still dont know why its not working.

推荐答案

请尝试以下类似方法:

var app = angular.module("app", [])
            .controller("controller", function ($scope, WebFactory) {
                $scope.data = "data";
                $scope.error = "error";
                $scope.data = {}
                WebFactory.getData().then(function success(response) {
                        $scope.data = response.data;
                    });
            })
            .factory("WebFactory", function ($http) {
                var obj = {};

                obj.getData = function()
                {
                    return $http({
                        method: "GET",
                        url: "http://localhost:37103/api/employee",                      
                    })
                }
                return obj;
            });

这篇关于AngularJS-无法使用工厂调用http服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆