本文介绍了Angularjs $ http.get不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的服务器端(ASP.ne MVC)我有方法,它看起来像这样:

on my server side (ASP.ne MVC) I have method which looks like this:

    [HttpGet]
    public JsonResult GetTrenings(string treningId)
    {
        var tempId = Guid.Parse(treningId);
        var trening = TreningService.GetTreningById(tempId);
        _trenings = TreningService.GetAllTreningsForUser(trening.UserId);
        return Json(_trenings, JsonRequestBehavior.AllowGet);

    }

和我有角服务:

publicApp.angularModule.factory('feedSingleTreningService', function ($q, $http) {

return {
   getTrenings: function (data) {
       var input = $http.get("/Feed/GetTrenings", { params: { treningId: data } });


        var deferred = $q.defer();

        deferred.resolve(input);
        return deferred.promise;
    },

};
});

在我的控制器我这样调用这个服务:

And In my Controller I call this service like this:

 feedSingleTreningService.getTrenings(data).then(function(results) {
        console.log("test", results);
    });

但没有什么是在控制台中显示,我已经调试服务器端请求到达它,它返回_trenings,也服务返回的承诺,但没有任何反应。

But nothing is shown in console, I've debugged server side and request reaches it, and it returns _trenings, also service returns promise, but nothing happens.

我已经改变,那​​么最终,在控制台的测试结果显示,但结果是不确定的。

I've changed then to finally, and in console "test" was shown but results were undefined.

为什么会出现这种情况?

Why is this happening ?

推荐答案

您不需要您的来电推迟至$ HTTP,因为它已经返回的承诺。

You don't need to defer your call to $http because it already returns a promise.

就返回

return $http.get("/Feed/GetTrenings", { params: { treningId: data } });

那么任何调用你的函数可以这样做:

then anything that calls your function can do:

getTrenings(myData).then(function(data) { do something }).fail(function() { error });

这篇关于Angularjs $ http.get不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:59