Because you know you will need a comment service to handle getting and adding comments, you need to add that first. Listing 27.15 implements a comment service that uses the service method. You need to create a function definition called CommentObj
. The constructor function accepts the $http
service as the only parameter.
You define a getComment()
function that accepts commentId
and then does a GET
request to the /comment/get
route to get the full comment data. Notice that this function also accepts a callback function. The callback function returns an error if $http
reports one or the comment data from the server.
The addComment()
function accepts rootCommentId
for the comment thread, parentId
for the parent comment, and a newComment
parameter that is a JavaScript object with subject
and body
properties. It then does a POST
request to /comment/add
to add the new comment to MongoDB. Just as with getComment()
, a callback function is executed and returns the results. Then the service is created using the following line to inject $http
:
app.service('commentSrv', ['$http', CommentObj]);
Then you can inject the commentSrv
service into your controllers.
02 function CommentObj($http) {
03 this.getComment = function(commentId, callback){
04 $http.get('/comments/get', {params: {commentId: commentId}})
05 .success(function(data, status, headers, config) {
06 callback(null, data);
07 })
08 .error(function(data, status, headers, config) {
09 callback(data, {});
10 });
11 };
12 this.addComment = function(rootCommentId, parentId,
13 newComment, callback){
14 $http.post('/comments/add', { rootCommentId: rootCommentId,
15 parentCommentId: parentId,
16 newComment: newComment })
17 .success(function(data, status, headers, config) {
18 callback(null, data);
19 })
20 .error(function(data, status, headers, config) {
21 });
22 };
23 }
24 app.service('commentSrv', ['$http', CommentObj]);