javascript - Angular JS : Promise returns resource

标签 javascript asp.net-mvc angularjs promise asp.net-web-api

存储库方法

public int CalculateSoundVolume(string roomName, int currentUser)
{

        {

            //Business Logic

            return finalApplauseVolume;  //**say returning 75**

        }
        catch (Exception ex)
        {
            _logger.LogException(ex);
            throw;
        }                                                                                                                          
 }
<小时/>

WEB API Controller

    public IHttpActionResult CalculateSoundVolume()
    {
        try
        {
            //Some Logic 
             var result = _applauseRepository.CalculateSoundVolume(huddleName, currentUser);
            return Ok(result); // **it returns 75 here in result**
        }
        catch (Exception ex)
        {
            _logger.LogException(ex);
            throw;
        }
    }
<小时/>

客户端 Controller (ANGULAR JS)

 public calculateSoundVolume() 
 {
    var promise = this.applauseService.calculateSoundVolume();
    promise.then((res) => {
        this.$log.debug("Sound Volume : ", res);
        // Getting Resource [0] : '7' and [1] : '5'
    });
 }
<小时/>

服务

   calculateSoundVolume() 
   {
    return this.soundVolume.get().$promise;        
    }
<小时/>

现在的情况是我从存储库方法返回一个整数值。 (比如75)。在 WEB API Controller 中,收到的结果值为 75。 但问题出在我的客户端 Controller 的“res”中,我收到的资源为 [0]:'7' 和 [1]:'5',即未收到实际值和预期值。请提出任何解决方案

最佳答案

同样的问题也发生在我身上。结果 $promise 不是返回 int,而是返回一个对象,该对象将整数的数字分解为数组中的不同索引以及 Promise 使用的一些其他信息。我能够通过用 JObject 包装整数并从 Web API 传递该整数而不是整数来解决该问题。

因此您的 Web API 将如下所示:

public JContainer CalculateSoundVolume()
{
    try
    {
        //Some Logic 
         var result = new JObject(new JProperty("soundVolume", _applauseRepository.CalculateSoundVolume(huddleName, currentUser)));
        return result;
    }
    catch (Exception ex)
    {
        _logger.LogException(ex);
        throw;
    }
}

您的客户端 Controller 将更改为:

public calculateSoundVolume()
{
     var promise = this.applauseService.calculateSoundVolume();
     promise.then((res) => {
         this.$log.debug("Sound Volume : ", res.soundVolume);
});

希望有帮助

-- 编辑--

我应该澄清一下,我在上面的代码中使用了 Newtonsoft 库来处理 JSON。我发现了另一个与 Here 相关的 stackOverflow 问题。总之,Chandermani 是正确的,您应该尝试从服务器发回有效的 JSON 对象。

关于javascript - Angular JS : Promise returns resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23195235/

相关文章:

javascript - 将 Json 解析为状态

mysql - IEnumerable 从 mySQL 连接打印出单个实体

c# - 如何使用 Orchard.Forms 插入保存按钮?

javascript - AngularJS 通过文本设置选定选项

angularjs - Angular 新路由器 - 嵌套组件和路由

javascript - 如何删除 Firestore 子集合中的文档

javascript - 在没有闭包/包装函数的情况下获取范围内的变量

asp.net-mvc - ASP.NET MVC ActionResult 背后的推理是一个抽象类?

javascript - 如何在javascript中进行元素提取?

javascript - 如何使用 JavaScript 排列 HTML 表格的列