AngularFire $add—TypeError: undefined is not a function

て烟熏妆下的殇ゞ 提交于 2019-12-08 04:16:13

问题


When I try to substitute $add for push, I get this error.

TypeError: undefined is not a function
at Scope.$scope.sendComment (http://localhost:9000/scripts/controllers/post.js:22:38)
at http://localhost:9000/bower_components/angular/angular.js:10847:21
...

Here's my controller @ post.js

16   $scope.sendComment = function () {
17     var newComment = {
18       user: $scope.currentUser,
19       text: $scope.currentText
20
21     }; 
22     var promise = CommentService.add(newComment);
23     promise.then(function(name) {
24       console.log(name);
25     });
26   };

Here's my service (the problematic add function is toward the bottom)

(function(angular) {
  'use strict';

   angular.module('codesApp').service('CommentService', function(FBURL, $q, $firebase) {
     var commentRef = new Firebase(FBURL).child('comments');
     var fireComment = $firebase(commentRef);
     return {
       childAdded: function childAdded(limitNumber, cb) {
         commentRef.startAt().limit(limitNumber).on('child_added', function(snapshot) {
           var val = snapshot.val();
           cb.call(this, {
             user: val.user,
             text: val.text,
             name: snapshot.name()
           });
         });
       },
       add: function addComment(comment) {
         return fireComment.$add(comment);
       },
       ....

I've been stuck on this all night. Any help is hugely appreciated! Thanks!


回答1:


$firebase(commentRef) only gets you half way to a firebase array that can call $add().

You must additionally call $asArray() on the return value of $firebase(commentRef) like so:

var fireCommentArray = $firebase(commentRef).$asArray();

Then you can

fireCommentArray.$add(comment)


来源:https://stackoverflow.com/questions/26435066/angularfire-add-typeerror-undefined-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!