我是初学者,学习Angularjs。请帮我提供以下示例
脚本已添加
javascript -
var app = angular.module('myapp', []);
app.controller('MyCtrl1', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.get({}, function (userFactory) {
$scope.time = userFactory.time;
})
}]);
var service = angular.module('apiService', ['ngResource']);
service.factory('UserFactory', function ($resource) {
return $resource('http://time.jsontest.com', {}, {
query: {
method: 'GET',
params: {},
isArray: true
}
})
});
.html文件
<body ng-app="myapp">
<divng-controller="MyCtrl1" >
<p>
Result from RESTful service is: {{ time }}
</p>
</div>
</body>
上面的片段给出了输出
RESTful服务的结果是:{{time}}
而不是我期待的价值 ..参考:http://draptik.github.io/blog/2013/07/13/angularjs-example-using-a-java-restful-web-service/
我想编写CRUD方法(GET / POST / PUT / DELETE),我已经开始使用GET了。
由于
答案 0 :(得分:1)
您需要确保主应用程序模块注入您的服务。在你的plnkr中你有:
var app = angular.module('myapp', []);
你应该拥有的地方:
var app = angular.module('myapp', ['apiService']);
这可确保将服务模块注入到您的app模块中,并且您可以使用在该模块中定义的UserFactory。对于这个简单的情况,您也可以简单地在'myapp'模块上定义UserFactory工厂
答案 1 :(得分:1)
它非常接近,但您的应用实例化中存在轻微错误。它应该如下:
var app = angular.module('myapp', [ 'apiService' ]);
我还看到了其他一些问题,但有一点是我通常会针对异步请求执行以下操作
var promise = UserFactory.get({}).$promise;
promise
.then( function(response) {
$scope.time = userFactory.time;
});
编辑:以下是给定ReST服务的命名方法的示例:
return $resource('/api/v2.0/user/lists/:listId',
{},
{
// POST - list create/product addition to list
'addProduct': {
method: 'POST',
isArray: false,
params: {
listId: '@listId',
productId: '@productId'
}
},
'createList': {
method: 'POST',
isArray: false,
params: {
listName: '@listName'
}
},
// GET - list of user lists/list details
'readLists': {
method: 'GET',
isArray: false,
params: {}
},
'readListsWithProductId': {
method: 'GET',
isArray: false,
params: {
productId: '@productId'
}
},
'readListById': {
method: 'GET',
isArray: false,
params: {
listId: '@listId',
sort: '@sort',
flags: true,
extendedInfo: true,
rows: '@rows',
start: '@start'
}
},
// PUT - list renaming
'renameList': {
method: 'PUT',
isArray: false,
params: {
newName: '@listName',
listId: '@listId'
}
},
// DELETE - list deletion/clear/product removal
'removeProduct': {
method: 'DELETE',
isArray: false,
params: {
listId: '@listId',
productId: '@productId'
}
},
'clearList': {
method: 'DELETE',
isArray: false,
params: {
listId: '@listId',
clear: true
}
},
'deleteList': {
method: 'DELETE',
isArray: false,
params: {
listId: '@listId'
}
}
});
您可以像以下一样访问它:
Factory.[methodName](payload)