Error: Undefined Function [Thinkster.io's Angular Tutorial Chapter 4]

Currently working on the Angular Tutorial provided by Thinkster.io and enjoying every bit of it. However, I've hit a roadblock in Chapter 4 that seems impossible to overcome. Whenever I attempt to execute a Post or Delete action, I encounter the following error:

TypeError: undefined is not a function
    at Object.Post.create (http://localhost:9000/scripts/services/post.js:12:20)
    at Scope.$scope.submitPost (http://localhost:9000/scripts/controllers/posts.js:9:10)
    at http://localhost:9000/bower_components/angular/angular.js:10795:21
    at http://localhost:9000/bower_components/angular/angular.js:19036:17
    at Scope.$eval (http://localhost:9000/bower_components/angular/angular.js:12632:28)
    at Scope.$apply (http://localhost:9000/bower_components/angular/angular.js:12730:23)
    at HTMLFormElement.<anonymous> (http://localhost:9000/bower_components/angular/angular.js:19035:21)
    at HTMLFormElement.jQuery.event.dispatch (http://localhost:9000/bower_components/jquery/dist/jquery.js:4409:9)
    at HTMLFormElement.elemData.handle (http://localhost:9000/bower_components/jquery/dist/jquery.js:4095:28)

-

Below is my implementation in app/scripts/app.js:

'use strict';
/* global app:true */

/**
 * @ngdoc overview
 * @name angNewsApp
 * @description
 * # angNewsApp
 *
 * Main module of the application.
 */

var app = angular.module('angNewsApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'firebase'
])
.constant('FIREBASE_URL', 'https://blazing-fire-1894.firebaseio.com/');
app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/posts.html',
        controller: 'PostsCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

-

app/services/post.js:

'use strict';

app.factory('Post',
  function ($firebase, FIREBASE_URL) {
  var ref = new Firebase(FIREBASE_URL + 'posts');

  var posts = $firebase(ref);

  var Post = {
    all: posts,
    create: function (post) {
      return posts.$add(post);
    },
    find: function (postId) {
      return posts.$child(postId);
    },
    delete: function (postId) {
      return posts.$remove(postId);
    }
  };

  return Post;
});

-

'app/scripts/controllers/posts.js':

'use strict';

app.controller('PostsCtrl', function ($scope, Post) {
  $scope.posts = Post.all;

  $scope.post = {url: 'http://', 'title': ''};

  $scope.submitPost = function () {
    Post.create($scope.post).then(function () {
      $scope.post = {url: 'http://', 'title': ''};
    });
  };

  $scope.deletePost = function (postId) {
    Post.delete(postId);
  };

});

-

app/views/posts.html:

<div ng-repeat='(postId, post) in posts'>
  <a href='{{ post.url }}'>{{ post.title }}</a> <a ng-click="deletePost(postId)">[X]</a>
</div>

<form ng-submit='submitPost()'>
    <input type='text' ng-model='post.title' />
    <input type='text' ng-model='post.url' />
    <input type='submit' value='Add Post' />
</form>

Preview: <a href='{{ post.url }}'>{{ post.title }}</a>

-

Included scripts in app/index.html

<!-- build:js(.) scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/json3/lib/json3.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script src="bower_components/angular-resource/angular-resource.js"></script>
    <script src="bower_components/angular-cookies/angular-cookies.js"></script>
    <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-touch/angular-touch.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/firebase/firebase.js"></script>
    <script src="bower_components/angularfire/dist/angularfire.min.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

        <!-- build:js({.tmp,app}) scripts/scripts.js -->
        <script src="scripts/app.js"></script>
        <script src="scripts/controllers/posts.js"></script>
        <script src="scripts/controllers/about.js"></script>
        <script src="scripts/services/post.js"></script>
        <!-- endbuild -->

-

If anyone has any insights on how to resolve this issue, I would greatly appreciate your input!

Answer №1

When dealing with the expectation of having an array of posts that can be manipulated by adding or deleting items.

It is necessary to modify this line:

var posts = $firebase(ref);

to the following:

var posts = $firebase(ref).$asArray();

I trust that this adjustment will be beneficial to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js throwing error due to incorrect format of bind parameters as an array

I have been working with Nodejs/express and trying to implement a paramerized query in my API. However, I encountered the following error message in my console: Bind parameters must be array if namedPlaceholders parameter is not enabled Below is a snippet ...

Retrieve user input from an HTML form and pass it as a parameter in a jQuery AJAX request

Is there a way to pass a value from a user input in an HTML file to jQuery.ajax? Take a look at the code snippet from my JS file: jQuery(document).ready(function() { jQuery.ajax({ type: 'POST', url: 'myurl.asp ...

Unlocking the value of the "input" field within an EventListener function in Angular directly from the DOM

In my "characters" module, there is a form with a text field and a button. When the button is clicked, it triggers a function but I am struggling to retrieve the current input text and pass it to the async function. HTML: https://i.sstatic.net/DMF8w.png ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

How can I ensure a successful redirect to react-router root path after saving to MongoDB in Express?

As a newcomer to React and react-router, I may be making some rookie mistakes in my project. Currently, I am constructing a web application with React and react-router as the frontend server, paired with Express and MongoDB for the backend. To communicate ...

What is the best way to view and use the data stored within this JSON object?

Obtaining information from a straightforward API (). I retrieve the data using getJSON: var police = $.getJSON(queryurl); A console.log on police displays this: However, I am unable to access the properties within the object. I assumed that I could ac ...

Escape from the chains of node.js then() statements

While working with a large amount of externally sourced data, I encounter situations where I need to interrupt the chain of commands and redirect the page. This is an example of my setup: Api file gamesApi.getAllResultsWithTeamInformation(passData) ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Navigating React Redux Pages Using React Router

At the moment, I am exploring the possibility of creating an application using React and Redux. Most examples I've come across make use of React Router, so I'm curious about its purpose. My application will consist of multiple pages (at least 20 ...

What is the best method for choosing a document from a Firebase based on its creation time?

Currently delving into Firebase as part of my project, struggling with setting queries in the Database. I've provided a breakdown of my Firebase database structure below: Looking to retrieve the most recently created document from the 'subscrip ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

Transferring an array of data across different screens within an Ionic 2 application

I am a newcomer to Ionic 2 and I am encountering difficulties when it comes to passing data between pages. Within my Home.ts file, there exists a global array containing certain numbers that have been calculated. My intention is to transfer this array to m ...

Steps to showcase a form on a webpage using a button

My webpage features an HTML table with a table navigation bar that allows users to add items or inventory. However, when the "add item" button is clicked, a form appears below the table instead of on top of it. I want the form to display itself right on to ...

Whenever a menu option is clicked in Umbraco, the page always redirects to the route #/content

After updating my site to the latest version available, I encountered a problem: Whenever I click on any link in the menu on the admin page (/umbraco) The temporary solution I discovered is Click on the link Go to profile Edit Confirm that you want to ...

Is it necessary for the Resource Server to have endpoints for 'Authorize' and 'Token' in OAuth implementation?

My current work assignment involves integrating an External Login feature into one of our applications. The goal is to allow users to log in to Application A using their credentials from Application B. For Application B, I have been given access to variou ...

What is the best way to expand an object without including any null values?

Imagine a scenario where there is an object: var user = { "Name": "Dan", "Age": 27, "Hobbies": null }; and it needs to be merged with the following base object to ensure all necessary properties are present: var base = { "Name": nul ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

"Enhance your website with captivating Javascript hover effects for

Can anyone assist me with incorporating the navigation hover effect seen on this website into my HTML/CSS project? The example site is built using a WordPress theme, but I am looking to apply that green effect to my own webpage and have the ability to cust ...

After calling the use method in Express, utilizing the get method

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use((req, res, next) => { console.log("Executing first middlewar ...