Angular.js and DAO design pattern

Admitting my newness to Angular.js and lack of experience with frameworks like Backbone or Knockout, I am venturing into building an application that interacts with a server using a RESTful API. After delving deep into the angular documentation and blog posts, I feel equipped to do it right.

I stumbled upon examples mostly utilizing $resource. It seems promising: with many built-in methods, designing your REST interface properly can eliminate the need for additional code.

However, my team and I are more accustomed to the JavaEE approach to the model layer: lightweight model classes (POJO, etc), DAO classes handling data persistence and retrieval, possibly a service layer between DAO and controllers. On the flip side, $resource in Angular creates something akin to active record.

I've brainstormed two ways to implement the DAO pattern in Angular:

  1. Starting from scratch, working at the $http abstraction level, implementing every method as an $http call while handling errors.
  2. Leveraging $resource objects as lightweight model classes and passing them to DAOs responsible for invoking actions like .$save(). Although not foolproof against misuse, this convention suffices for me.

The second approach appeals to me due to code reusability. $resource offers promise object functionality, which saves me from reinventing the wheel.

Now, onto the crucial queries: is an active record approach the only way to achieve efficient data access in Angular, Backbone, and similar tools? Has anyone experimented with integrating a DAO-like solution into their code and would care to share insights?

Additionally, is the $resource object equipped to handle errors, connection disruptions, and other issues effectively? Given these considerations, is it advisable to stick with $resource or begin at a lower level with $http?

Being in the project's early stages, I understand the gravity of this decision and aim to make the best choice for its longevity.

Answer №1

I completely concur. This is my preferred method:

bankApp.factory("CustomerRepository", function ($resource) {
    var customerRepo = $resource("rest/customers/:id", {id:'@id'}, {'update': {method:'PUT'}});
    // You can extend the customerRepo with additional functionality like making $http calls
    return customerRepo;
});

Then you can use the CustomerRepository wherever it's needed. For instance:

bankApp.controller("BankController", function ($scope, CustomerRepository) {

    $scope.customers = CustomerRepository.query();

    $scope.createCustomer = function () {
        CustomerRepository.save($scope.customer, function (customer) {
            ...
        });
    };

    ...

    $scope.saveCustomer = function () {
        CustomerRepository.update($scope.customer, function (customer) {
            ...
        });
    };
});

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

Issue with Ajax call not triggering the Controller Action in MVC

I am encountering an issue with making an ajax call to the controller action method that returns a json object. In addition, I need to pass the integer CheckID to the method. Any assistance would be greatly appreciated. Thank you in advance! ***View*** ...

What is the best way to retrieve the source code generated by Ajax

I designed a PHP script that generates text dynamically and returns it with a unique div id. However, when I use Ajax to retrieve this text as responseText, I am unable to access the properties of the div using JavaScript because the new text is not added ...

Vue: Load page content only after the route change is complete

Every time I visit a new route within the current session, I notice that the page loads and then takes about 2 seconds for the styles to be applied. This delay causes what is commonly known as CSS flashing or FOUC (Flash of Unstyled Content), which ultimat ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

React fails to recognize the key prop

When creating a list of TSX elements, I utilized the following code: this.productsModel = this.state.products.map(o => ( <Grid.Column key> However, I encountered a warning from React: Warning: Each child in a list should have ...

contrasting ionic and android software development kits

I am interested in developing an android application and have some knowledge about Ionic, which is also used for creating mobile apps. I have more experience with Android development and am curious to understand the distinctions between the two platforms ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

Tips for defining a relative path in the base URL with AngularJS

Encountering an issue with AngularJS routes related to file paths. The folder structure is as follows: js -> Angular -> css -> Bootstrap -> index.html Routes work fine when hosted on a server like IIS. However, copying and pasting the direct ...

What is the best way to extract a state from a URL utilizing ui-router?

If I have something similar to this scenario: {ui-sref="tab({tabid:3})"} Once the element with the above attribute is clicked, it will trigger a state that results in a URL such as /tab/:tabid. For instance, http://..../tab/3 However, here lies my issu ...

Using Console.log() will display 'undefined' prior to receiving any data

I am facing a problem with a lifecycle hook that I have been trying to troubleshoot. export default class EditRevision extends Component { state = { data: [], customColumns: [] } componentWillMount = () => { axios.get('http:/ ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

Guide on using JavaScript to extract and display a random text from a datalist upon clicking with the onclick event

Is there a way for a JavaScript function to select a random sentence from a datalist within the same file and display it upon clicking a button with an "onclick" event? I'm new to JavaScript and seeking the simplest solution. Can anyone provide an exa ...

Leverage array mapping functionality to generate React components within a separate component

Currently, I am retrieving data from an API and storing the results in an array. The issue arises when trying to map the array to a child component since it is initially empty. How can I ensure that the array mapping only executes when there is data in the ...

Encountering a Problem: [$injector:modulerr] Inability to Create App Module in AngularJS + Karma + Jasmine Setup

We are currently working on a large project that involves multiple controllers, factories, configs, and more. Recently, I decided to integrate karma+ jasmine for writing unit test cases. However, I am encountering the error mentioned above. Despite trying ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...

Looking for a solution to tackle this error message? Issue: Notice - Undefined property: stdClass::

click here for imageI'm encountering an issue while attempting to present a table from a MySQL database using CodeIgniter and AngularJS. What mistake am I making? Below is my view file: list_show_data.php <?php defined('BASEPATH') OR exi ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...

AngularJS: The delay in updating variable bindings following a REST API call

When utilizing a REST service, I wanted to implement a variable to show whether the service is currently loading or not. Controller $scope.loading = true; $http.get('/Something'). success(function(data, status, headers, config) ...

Is there a way to create a popover menu in VueJS without using JQuery

I found exactly what I need in this helpful answer. It demonstrates a menu appearing when clicking on a table row. The dilemma is that it relies on JQuery... Therefore, I am curious if achieving the same functionality without JQuery is possible. Maybe thr ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...