【问题标题】:angularjs access web api through serviceangularjs通过服务访问web api
【发布时间】:2015-10-28 22:21:12
【问题描述】:

我想将web api中的值返回到javascript文件,但我一直无法获取数据,谁能帮我找出问题所在? 我尝试使用http://localhost:8584/api/Testing/5 来检查是否有任何结果。

//thsi is the javascript controller who called the service.js
app.controller('mainController', function ($scope, service) {
    
    returnData();
    function returnData() {
        var getData = service.get(5);

        //the data return from web api would shown by $scope.newmessage
        getData.then(function (pl) { $scope.newmessage = pl.data },
              function (errorPl) {
                  $log.error('failure loading Employee', errorPl);
              });
    }
}
            
//this is service.js
app.service('service', function ($http) {
    
    var bseUrl = 'http://localhost:8584/';
    this.get = function (Id) {
        return $http.get(baseUrl + 'api/Testing/' + Id);
    }
});


//thsi is my web api controller
namespace angulartestOne.Controllers
{
    public class TestingController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}

【问题讨论】:

  • 乍一看,您是在服务中声明 bseUrl,然后尝试使用 baseUrl。
  • 那么假设基本网址应该是什么样的?
  • var 名称无关紧要我只是指出您没有使用您声明的 var。
  • 您是否将 localhost webapi 应用程序置于调试模式并查看请求是否通过 API 的 get 方法?
  • 嗨,谢谢你的所有建议,但它仍然没有工作;我有一条错误消息,如我在下面发布的答案所示......你能帮我看看吗?谢谢

标签: javascript angularjs asp.net-web-api


【解决方案1】:

我认为您需要在数据准备好时从服务的 get 方法中进行回调。请注意,这都是异步的,只有在数据可用时才能返回。

重写你的服务如下

app.service('service', function ($http) {
  var bseUrl = 'http://localhost:8584/';
  this.get = function (Id) {
     $http.get(baseUrl + 'api/Testing/' + Id)
      .then(function (response) {
           return response.data;
      });
     }
   });

【讨论】:

  • 嗨,感谢您的建议,但它仍然没有工作;我有一条错误消息,如我在下面发布的答案所示......你能帮我看看吗?谢谢
猜你喜欢
  • 2017-02-15
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多