简体   繁体   English

从angularjs调用RESTful服务的正确方法

[英]Proper way to call RESTful service from angularjs

I am trying to do a simple todo app with RESTful api. 我正在尝试使用RESTful API做一个简单的待办事项应用程序。 My restful service returns the below JSON, 我的RESTful服务返回以下JSON,

[{"title":"completed this","completed":false},{"title":"and this too","completed":false}]

Returned as a application/json not a string. 作为应用程序/ json返回,而不是字符串。

My view is as below, 我的看法如下

<div class="container" ng-app="todomvc">
        <div id="todoapp" ng-controller="TodoCtrl">
             <div class="row" ng-repeat="todo in todos">         
             {{todo.title}}
             </div>
        </div>
</div>

And I have the below JS code with controller and a factory, 我有以下带有控制器和工厂的JS代码,

var todomvc = angular.module('todomvc', []);

todomvc.factory('todoREST', function ($q,$http) {
 function get(){
   return $http.get('http://localhost/test.php');
 }
 return{get:get};
});

todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, $filter, todoREST) {
    var todos = $scope.todos = todoREST.get().then(function(data){
    todos = data.data;
    console.log(todos); // Data available here
    });
});

I am unable to get the title in the page when it is loaded. 加载页面时,无法在页面中获取标题。 What am I doing wrong? 我究竟做错了什么? And is my approach the right way to make a RESTful call? 我的方法是进行RESTful通话的正确方法吗?

Here is a link to what I have done, http://plnkr.co/edit/kaSCe9HoMPEK1hD4QgJl?p=preview 这是我所做的链接, http://plnkr.co/edit/kaSCe9HoMPEK1hD4QgJl?p = preview

You're assigning $scope.todos to the promise returned by the service, not the data from the callback. 您正在将$ scope.todos分配给服务返回的promise,而不是回调中的数据。

Try 尝试

todoREST.get().then(function(data){
    $scope.todos = data.data;
    console.log($scope.todos); // Data available here
});

http://plnkr.co/edit/C3fbK3NicU7XkdHAbzCr?p=preview http://plnkr.co/edit/C3fbK3NicU7XkdHAbzCr?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM