Featured

Angular 8 – Upload/Display/Delete files to/from Firebase Storage using @angular/fire

In this tutorial, ozenero.com shows you way to upload, get, delete Files to/from Firebase Storage in a simple Angular 8 App using @angular/fire. Files’ info will be stored in Firebase Realtime Database.

Related Posts:
Angular 8 Firebase tutorial: Integrate Firebase into Angular 8 App with @angular/fire
Angular 8 Firebase CRUD operations with @angular/fire
Angular 8 Firestore tutorial with CRUD application example – @angular/fire

Want to know to to deploy Angular App on Hostings?
>> Please visit this Series (with Instructional Videos)

Continue reading “Angular 8 – Upload/Display/Delete files to/from Firebase Storage using @angular/fire”

Featured

Django RestApis CRUD Application with Angular 6 & PostgreSQL tutorial

In this tutorial, we show you Angular 6 Http Client & Django Server example that uses Django to do CRUD with PostgreSQL (including finder method) and Angular 6 as front-end technology to make request and receive response.

Related Post: Django RestApis example – GET/POST/PUT/DELETE requests to PostgreSQL database

Continue reading “Django RestApis CRUD Application with Angular 6 & PostgreSQL tutorial”

Featured

Vue.js + Spring Boot example | Spring Data JPA + REST + MariaDB CRUD

Tutorial: Vue.js SpringBoot CRUD MariaDB Example | Spring Data JPA + REST + MariaDB CRUD

In this Vue.js SpringBoot tutorial, we show you Vue.js Http Client & Spring Boot Server example that uses Spring JPA to do CRUD with MariaDB and Vue.js as a front-end technology to make request and receive response.

Related Posts:
MariaDB – How to use Spring JPA MariaDB | Spring Boot
Vue Router example – with Nav Bar, Dynamic Route & Nested Routes
Reactjs JWT Authentication Example

Continue reading “Vue.js + Spring Boot example | Spring Data JPA + REST + MariaDB CRUD”

Implement LSTM Network using Python with TensorFlow and Keras for prediction and classification

A powerful type of Recurrent Neural Networks – Long Short-Term Memory (LSTM) is not only transmitting output information to the next time step, but they are also storing and transmitting the state of the so-called LSTM cell. This cell contains four neural networks – gates that determine which information is stored in the cell state and pushed to output. As a result, the output of the network at a one-time step is dependent on n previous time steps rather than just the previous time step.

In this article, we will look at two similar language modeling problems and see how they can be solved using two different APIs. To begin, we will build a network that can predict words based on the provided text, and we will use TensorFlow for this. In the second implementation, we will use Keras to classify reviews from the IMDB dataset.

Implement a Model with Tensorflow

The DataHandler class in DataHandler.py will be used. This class serves two functions: it loads data from a file and assigns a number to each symbol. The code is as follows:

import numpy as np
import collections

class DataHandler:
    def read_data(self, fname):
        with open(fname) as f:
            content = f.readlines()
        content = [x.strip() for x in content]
        content = [content[i].split() for i in range(len(content))]
        content = np.array(content)
        content = np.reshape(content, [-1, ])
        return content
    
    def build_datasets(self, words):
        count = collections.Counter(words).most_common()
        dictionary = dict()
        for word, _ in count:
            dictionary[word] = len(dictionary)
        reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
        return dictionary, reverse_dictionary

We will create a new class RNNGenerator in rnn_generator.py that can generate an LSTM network based on the parameters passed in.

import tensorflow as tf
from tensorflow.contrib import rnn

class RNNGenerator:
    def create_LSTM(self, inputs, weights, biases, seq_size, num_units):
        # Reshape input to [1, sequence_size] and split it into sequences
        inputs = tf.reshape(inputs, [–1, seq_size])
        inputs = tf.split(inputs, seq_size, 1)
    
        # LSTM with 2 layers
        rnn_model = rnn.MultiRNNCell([rnn.BasicLSTMCell(num_units),rnn.BasicLSTMCell(num_units)])
    
        # Generate prediction
        outputs, states = rnn.static_rnn(rnn_model, inputs, dtype=tf.float32)
    
        return tf.matmul(outputs[–1], weights['out']) + biases['out']

TensorFlow itself, as well as the RNN class from tensorflow.contrib, were imported. We will use our LSTM Network, which is a subtype of RNNs, to create our model. First, we reshaped our input and then divided it into three-symbol sequences. The model was then created.

Using the BasicLSTMCell method, we created two LSTM layers. The parameter num units specify the number of units in each of these layers. Aside from that, we use MultiRNNCell to integrate these two layers into a single network. The static RNN method was then used to build the network and generate predictions.

Finally, we will employ the SessionRunner class in session_runner.py. This class contains the environment used to run and evaluate our model. Here’s how the code works:

import tensorflow as tf
import random
import numpy as np

class SessionRunner():
    training_iters = 50000
            
    def __init__(self, optimizer, accuracy, cost, lstm, initilizer, writer):
        self.optimizer = optimizer
        self.accuracy = accuracy
        self.cost = cost
        self.lstm = lstm
        self.initilizer = initilizer
        self.writer = writer
    
    def run_session(self, x, y, n_input, dictionary, reverse_dictionary, training_data):
        
        with tf.Session() as session:
            session.run(self.initilizer)
            step = 0
            offset = random.randint(0, n_input + 1)
            acc_total = 0
        
            self.writer.add_graph(session.graph)
        
            while step < self.training_iters: if offset > (len(training_data) - n_input - 1):
                    offset = random.randint(0, n_input+1)
        
                sym_in_keys = [ [dictionary[ str(training_data[i])]] for i in range(offset, offset+n_input) ]
                sym_in_keys = np.reshape(np.array(sym_in_keys), [-1, n_input, 1])
        
                sym_out_onehot = np.zeros([len(dictionary)], dtype=float)
                sym_out_onehot[dictionary[str(training_data[offset+n_input])]] = 1.0
                sym_out_onehot = np.reshape(sym_out_onehot,[1,-1])
        
                _, acc, loss, onehot_pred = session.run([self.optimizer, self.accuracy, self.cost, self.lstm], feed_dict={x: sym_in_keys, y: sym_out_onehot})
                acc_total += acc
                
                if (step + 1) % 1000 == 0:
                    print("Iteration = " + str(step + 1) + ", Average Accuracy= " + "{:.2f}%".format(100*acc_total/1000))
                    acc_total = 0
                step += 1
                offset += (n_input+1)

Our model is being run through 50000 iterations. We injected the model, optimizer, loss function, and other information into the constructor so that the class could use it. Naturally, the first step is to slice up the data in the provided dictionary and generate encoded outputs. In addition, we are introducing random sequences into the model to avoid overfitting. The offset variable handles this. Finally, we’ll run the session to determine accuracy. Don’t be confused by the final if statement in the code; it’s just for show (at every 1000 iterations present the average accuracy).

Our main script main.py combines all of this into one, as shown below:

import tensorflow as tf
from DataHandler import DataHandler
from RNN_generator import RNNGenerator
from SessionRunner import SessionRunner

log_path = '/output/tensorflow/'
writer = tf.summary.FileWriter(log_path)

# Load and prepare data
data_handler = DataHandler()

training_data =  data_handler.read_data('meditations.txt')

dictionary, reverse_dictionary = data_handler.build_datasets(training_data)

# TensorFlow Graph input
n_input = 3
n_units = 512

x = tf.placeholder("float", [None, n_input, 1])
y = tf.placeholder("float", [None, len(dictionary)])

# RNN output weights and biases
weights = {
    'out': tf.Variable(tf.random_normal([n_units, len(dictionary)]))
}
biases = {
    'out': tf.Variable(tf.random_normal([len(dictionary)]))
}

rnn_generator = RNNGenerator()
lstm = rnn_generator.create_LSTM(x, weights, biases, n_input, n_units)

# Loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=lstm, labels=y))
optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001).minimize(cost)

# Model evaluation
correct_pred = tf.equal(tf.argmax(lstm,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
initilizer = tf.global_variables_initializer()

session_runner = SessionRunner(optimizer, accuracy, cost, lstm, initilizer, writer)
session_runner.run_session(x, y, n_input, dictionary, reverse_dictionary, training_data)

The content of meditations.txt is “In a sense, people are our proper occupation. Our job is to do them good and put up with them. But when they obstruct our proper tasks, they become irrelevant to us—like sun, wind, and animals. Our actions may be impeded by them, but there can be no impeding our intentions or our dispositions. Because we can accommodate and adapt. The mind adapts and converts to its own purposes the obstacle to our acting. The impediment to action advances action. What stands in the way becomes the way .”

We run the code and get accuracy above 95% with iteration 50000

Implement a model with Keras

This TensorFlow example was straightforward and simple. We used a small amount of data, and the network learned this fairly quickly. What if we have a more complicated issue? Assume we want to categorize the sentiment of each movie review on a website. Fortunately, there is already a dataset dedicated to this issue – The Large Movie Review Dataset (often referred to as the IMDB dataset).

Stanford researchers collected this dataset in 2011. It includes 25000 movie reviews (both positive and negative) for training and the same number of reviews for testing. Our goal is to build a network that can determine which reviews are positive and which are negative.

The power of Keras is that it abstracts a lot of what we had to worry about while using TensorFlow. However, it provides us with less flexibility. Of course, everything has a cost. So, let’s begin by importing the necessary classes and libraries.

There is a slight difference in imports between examples where we used standard ANN and examples where we used Convolutional Neural Network. We brought in Sequential, Dense, and Dropout. Nonetheless, we can see a couple of new imports. We used Embedding and LSTM from keras.layers. As you might expect, LSTM is used to create LSTM layers in networks. In contrast, embedding is used to provide a dense representation of words.

This is an interesting technique for mapping each movie review into a real vector domain. Words are encoded as real-valued vectors in a high-dimensional space, with similarity in meaning corresponding to closeness in the vector space.

We are loading the top 1000 words dataset. Following that, we must divide the dataset and generate and pad sequences. This is accomplished by utilizing sequence from keras.preprocessing

from keras.preprocessing import sequence 
from keras.models import Sequential 
from keras.layers import Dense, Dropout, Embedding, LSTM 
from keras.datasets import imdb 

num_words = 1000 
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=num_words) 

X_train = sequence.pad_sequences(X_train, maxlen=200) 
X_test = sequence.pad_sequences(X_test, maxlen=200)

# Define network architecture and compile 
model = Sequential() 
model.add(Embedding(num_words, 50, input_length=200)) 
model.add(Dropout(0.2)) 
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2)) 
model.add(Dense(250, activation='relu')) 
model.add(Dropout(0.2)) 
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) 


model.fit(X_train, y_train, batch_size=64, epochs=10) 

print('\nAccuracy: {}'. format(model.evaluate(X_test, y_test)[1]))

We used the number 200 in the padding to indicate that our sequences will be 200 words long. This is how the training input data looks:

Sequential is used for model composition, as we have seen in previous articles. The first layer added to it is Embedding, which we discussed in the previous chapter. We added one LSTM layer after the word embedding was completed. Finally, because this is a classification problem, we add a dense layer with a sigmoid function to determine whether the review was good or bad. Finally, the model is compiled using binary cross-entropy and the Adam optimizer.

We got an accuracy of 85.05%

When developing LSTM networks, we observed two approaches. Both approaches dealt with simple problems and employed a different API. As can be seen, TensorFlow is more detailed and flexible; however, you must take care of a lot more details than when using Keras. Keras is simpler and easier to use, but it lacks the flexibility and possibilities that pure TensorFlow provides. Both of these examples produced acceptable results, but they could have been better. Especially in the second example, where we typically use a combination of CNN and RNN to improve accuracy, but that is a topic for another article.

The Benefits of Learning to Code

You have probably clicked on this guide because you are thinking about learning all the ins and outs of coding but are not sure as to whether the benefits involved are worth it. This is something worth thinking about when you consider that it takes around three to six months to learn just the very basics of coding. Nonetheless, it can easily be argued that the benefits of learning to code are manifold and make it a worthwhile investment. If you want to know what they are, then you are in the right place, as this guide will give you a complete overview.

Increases Intelligence

If you are looking to become more intelligent and simply just boost your smartness in general, then learning to code is a great idea. As it is a rather challenging experience, this means that if you do succeed in it, you will feel a great sense of accomplishment, boosting your mental health in the process, with studies even suggesting that people who learn to code are less likely to develop early-onset dementia. If you are looking to code, however, then you need to make sure that you have a good laptop and that it is transported safely. For sending delicate items, take a look around now for a great fragile goods transport service today.

Makes You More Employable

As the cost of living has gone up in the USA, it is more important than ever to have a high-paying job that can allow you to pay the bills no matter what you are doing or where you are living. This means that if you have the qualifications in particular coding languages, this means that you have something to talk about when it comes to a job interview. This means that you will definitely be a lot more employable, especially in high-paying tech jobs with a lot of great perks!

Transferrable Skills

When you learn how to code, this doesn’t necessarily mean that you have to get a job in website development or computer security. In fact, it doesn’t necessarily mean that you need to get a coding-related job at all. What coding does offer you, however, is one of the most transferrable skills out there. This means that even if you work in management or development, having that coding knowledge in your back pocket can help you massively.

Create Your Own Product

Programming, coding, and software development are all closely linked. This means that if you know to code, you will be able to actually think about making your own product or solution. The benefit of doing this is the vast economic potential of such a decision, as well as the fun and satisfaction that you will get out of solving a problem. Try and think now about a certain type of product or solution that you would like to see on the market; it’s likely that if you learn how to code, you might just be able to make that product a reality yourself.

Training and deploying machine learning models with TensorFlow.js JavaScript Library

Deep learning and machine learning algorithms can be executed on Javascript with TensorFlow.js. In the article, we will introduce how to define, train and run your machine learning models using the API of TensorFlow.js.

With a few lines of Javascript, developers can implement pre-trained models for complex tasks such as visual recognition, generating music, or human poses detection. Node.js allows TensorFlow.js can be used in backend Javascript applications rather than use Python.

TensorFlow Javascript

TensorFlow is a popular open-source software library for machine learning applications. Many neural networks and other deep learning algorithms use the TensorFlow library, which was originally a Python library released by Google in November 2015. TensorFlow can use either CPU or GPU-based computation for training and evaluating machine learning models. The library was originally developed to operate on high-performance servers with GPUs.

In May 2017, Tensorflow Lite, a lightweight version of the library for mobile and embedded devices, was released. This was accompanied by MobileNet, a new series of pre-trained deep learning models for vision recognition tasks. MobileNet models were created to perform well in resource-constrained environments such as mobile devices.

TensorFlow.js follow TensorFlow Lite, was announced in March 2018. This version of the library was built on an earlier project called deeplearn.js and was designed to run in the browser. WebGL allows for GPU access to the library. To train, load, and run models, developers use a JavaScript API.

TensorFlow.js is a JavaScript library that can be used to train and deploy machine learning models in the browser and Node.js. TensorFlow.js was recently extended to run on Node.js by using the tfjs-node extension library.

Are you familiar with concepts such as Tensors, Layers, Optimizers, and Loss Functions (or willing to learn them)? TensorFlow.js is a JavaScript library that provides flexible building blocks for neural network programming.

Learn how to use TensorFlow.js code in the browser or Node.js to get started.

Get Setup

Importing Existing Models Into TensorFlow.js

The TensorFlow.js library can be used to run existing TensorFlow and Keras models. Models must be converted to a new format using this tool before they can be executed. Github hosts pre-trained and converted models for image classification, pose detection, and k-nearest neighbors are available on Github.

Learn how to convert pre-trained Python models to TensorFlow.js here.

Learn by looking at existing TensorFlow.js code. tfjs-examples provide small code examples that use TensorFlow.js to implement various ML tasks. See it on GitHub

Loading TensorFlow Libraries

TensorFlow’s JavaScript API is accessible via the core library. Node.js extension modules do not expose any additional APIs.

const tf = require('@tensorflow/tfjs')
// Load the binding (CPU computation)
require('@tensorflow/tfjs-node')
// Or load the binding (GPU computation)
require('@tensorflow/tfjs-node-gpu')

Loading TensorFlow Models

TensorFlow.js includes an NPM library (tfjs-models) to make it easier to load pre-trained and converted models for image classification, pose detection, and k-nearest neighbors.

The MobileNet image classification model is a deep neural network that has been trained to recognize 1000 different classes.

The following example code is used to load the model in the project’s README.

import * as mobilenet from '@tensorflow-models/mobilenet';

// Load the model.
const model = await mobilenet.load();

One of the first issues I ran into was that this does not work on Node.js.

Error: browserHTTPRequest is not supported outside the web browser.

The mobilenet library is a wrapper around the underlying tf.Model class, according to the source code. When the load() method is invoked, the correct model files are automatically downloaded from an external HTTP address and the TensorFlow model is instantiated.

The Node.js extension does not yet support HTTP requests to retrieve models dynamically. Models must instead be manually loaded from the filesystem.

After reading the library’s source code, I was able to devise a workaround…

Loading Models From a Filesystem

If the MobileNet class is created manually, rather than calling the module’s load method, the auto-generated path variable containing the model’s HTTP address can be overwritten with a local filesystem path. After that, calling the load method on the class instance will invoke the filesystem loader class rather than the browser-based HTTP loader.

const path = "mobilenet/model.json"
const mn = new mobilenet.MobileNet(1, 1);
mn.path = `file://${path}`
await mn.load()

MobileNet Models

TensorFlow.js models are made up of two file types: a model configuration file in JSON and model weights in binary format. Model weights are frequently sharded into multiple files for better browser caching.

The automatic loading code for MobileNet models retrieves model configuration and weight shards from a public storage bucket at this address.

https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v${version}_${alpha}_${size}/

The URL template parameters refer to the model versions listed here. On that page, the classification accuracy results for each version are also displayed.

According to the source code, the tensorflow-models/mobilenet library can only load MobileNet v1 models.

The HTTP retrieval code loads the model.json file from this location and then recursively retrieves all model weights shards that are referenced. These files are in the groupX-shard1of1 format.

6 Tips for People Who Are Interested in Learning to Code

Learning to code might seem like a nice idea for a new hobby. At the same time, some people might be looking for new career opportunities, and despite some claims of how the programmer market is oversaturated, there is still plenty of room for newcomers. And this room exists particularly for those who are flexible and willing to learn.

Now, as a coder, you need to be familiar with computers. Knowing the ins and outs of different operating systems is valuable when you are choosing a setup for yourself.

Something as simple as understanding how to retrieve something from the clipboard on macOS or how to kill redundant processes in MS Windows shows how tech-savvy one is.

Of course, these things are pretty much the basics, and you can learn them pretty quickly. And speaking of which, our first tip is to focus on one’s fundamentals as a coder.

Have Strong Basics

Strong basics help build a foundation. Early on, you might not have that many problems figuring out simple problems and writing lines of code. However, as you advance, you will realize that things are quite hectic and problematic.

Missing fundamentals is a crucial mistake that can snowball out of control. As such, you need to work on creating a solid foundation so that you can expect fewer issues down the line.

How good your basics are comes down to the work rate and what learning method you pick. If you are going for formal education in a university or college, you can expect to benefit from tailor-made programs.

On the other hand, self-taught coders might find it a bit harder because they could end up missing a few crucial steps, which leaves a hole or two in their knowledge.

Going back and filling the missing pieces later is a possibility, but it is not necessarily the most efficient solution due to how much you might fall back on your work if you need to brush up on the basics.

Write Code by Hand

For some, the idea of writing a code on a piece of paper might seem counterintuitive. After all, you will be doing most of your work on a computer anyway, so why stick to an outdated method?

Well, there are multiple studies that suggest how taking notes makes it easier to remember things. The same principle applies to coding.

If you spend a bit of time writing down lines of code by hand, you are more likely to memorize the information.

Getting a pen and a piece of paper or a notebook is not that difficult, nor is it expensive. Even if it is just one page that you write, it is still a good push to become better.

Ask for Help

Asking for help is common among coders. Join one of the many available communities online or locally and start talking with other coders.

As a newbie, you are more than likely to run into various issues, and it is natural that more experienced people will have a solution.

The coding community is quite friendly, and even if you do not get to meet people in person, you can still make plenty of online acquaintances. And do not treat these connections as just solutions to potential problems. Networking comes in handy as well, particularly when you are looking for a job as a coder.

Utilize Available Sources Online

Other than the online communities, there are plenty of different resources that provide you with useful coding information.

For the most part, you will likely focus on learning. Video tutorials are easy to find on YouTube or platforms like Skillshare. Whether you are looking to learn the basics or more advanced pieces of code, both free and paid resources are available.

Take Breaks When Necessary

Spending too much time typing a code on your keyboard is not great for your health. If you get too much into coding, you might lose track of time.

Taking breaks is part of a healthy routine. Do not get in the habit of spending too much time in front of a computer’s screen. Even short five-minute breaks are a good change of pace.

Create an Optimal Workspace

The last bit of advice is about creating an optimal workspace. As a coder, you will have to be in front of a computer a lot, typing constantly.

For starters, make sure to find a comfortable keyboard. Try both membrane and mechanical keyboards to determine which one suits you the most.

A proper ergonomic chair is also a must. Do not be cheap, and avoid sitting in a chair that will cause damage to your back long-term.

Finally, get rid of distractions. You want to focus on coding when you are doing it, so make sure that you are not distracted by other people or things like random smartphone notifications.

Make Angular 13, MongoDB example with Node.js Express

The tutorial is an Angular 13 + MongoDB example with Node.js Express: CRUD. You can follow the introduction to create CRUD apps that use Angular 13 and Node js express rest API and MongoDB.

Following  the below steps to create Angular 13 + Node JS MongoDB crud application:

  • Step 1 – Create New Angular App
  • Step 2 – Create Components in Angular
  • Step 3 – Import Modules in app.module.ts
  • Step 4 – Create CRUD Routes
  • Step 5 – Build RESTful API using Node + Express js + MongoDB
  • Step 6 – Create Angular Service for REST API Consumption
  • Step 7 – Add code In app.component.html
  • Step 8 – Create Operation

Step 1 – Create New Angular App

First of all, open your terminal and execute the following command on it to install an Angular app:

Firstly, open your terminal and execute the  command to install an Angular app:

ng new my-new-app

Next, you need to execute the following command on the terminal to install angular material:

ng add @angular/material

Step 2 – Create Components in Angular

In this step, execute the following commands on the terminal to generate components in the angular application. Then, open your terminal and execute the below command:

ng g c components/add-book
ng g c components/book-detail
ng g c components/books-list

Step 3 – Import Modules in app.module.ts

In this step, visit the directory src/app and then open the file app.module.ts. After that you need to add the below code into the file:

...
...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [],
  imports: [
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: []
})
export class AppModule { }

Step 4 – Create CRUD Routes

In the step, you need to create routes with the help of Angular routes. You will make a consensus with components to enable the navigation in the CRUD application, then you need to add the following code in the app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BooksListComponent } from './components/books-list/books-list.component';
import { AddBookComponent } from './components/add-book/add-book.component';
import { BookDetailComponent } from './components/book-detail/book-detail.component';
const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'add-book' },
  { path: 'books-list', component: BooksListComponent },
  { path: 'add-book', component: AddBookComponent },
  { path: 'edit-book/:id', component: BookDetailComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 5 – Build RESTful API using Node + Express js + MongoDB

In the step, we will introduce how to create RESTful API with Node and Express.js. We will learn to use MongoDB and how to handle data.

You need to execute the following command to invoke the REST API development with Node and Express.js:

mkdir node-rest-api && cd node-rest-api

Then you need to execute the command:

npm init -y

Next, you execute the below commands to install imperative npm packages that will help you to create REST APIs for your Angular CRUD system:

npm install express cors body-parser mongoose
npm install nodemon --save-dev

In order to store the data flawlessly, you can use a reliable database of what else could be a better choice than MongoDB. So, execute the command to create a node-backend/database directory, and generate the db.js file where all the logic will be piled up for invoking the MongoDB connection.

mkdir database && cd database && touch db.js

Next, you need to add the following code in node-backend/database/db.js file.

module.exports = {
    db: 'mongodb://localhost:27017/db'
};

Now, you have to create the Book model or schema, and create node-backend/model folder. Also, you need to create a Book.js file and add the below code into the file:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Book = new Schema({
  name: {
    type: String
  },
  price: {
    type: String
  },
  description: {
    type: String
  }
}, {
  collection: 'books'
})
module.exports = mongoose.model('Book', Book)

Then, you need to define the REST API routes using Express js in the node project. Then you can create node-backend/routes folder, and create book.routes.js file. You need to add the below code into it:

const express = require('express');
const app = express();
const bookRoute = express.Router();
let Book = require('../model/Book');
// Add Book
bookRoute.route('/add-book').post((req, res, next) => {
    Book.create(req.body, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
});
// Get all Book
bookRoute.route('/').get((req, res) => {
    Book.find((error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})
// Get Book
bookRoute.route('/read-book/:id').get((req, res) => {
    Book.findById(req.params.id, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})
// Update Book
bookRoute.route('/update-book/:id').put((req, res, next) => {
    Book.findByIdAndUpdate(req.params.id, {
    $set: req.body
  }, (error, data) => {
    if (error) {
      return next(error);
      console.log(error)
    } else {
      res.json(data)
      console.log('Book updated successfully!')
    }
  })
})
// Delete Book
bookRoute.route('/delete-book/:id').delete((req, res, next) => {
    Book.findByIdAndRemove(req.params.id, (error, data) => {
    if (error) {
      return next(error);
    } else {
      res.status(200).json({
        msg: data
      })
    }
  })
})
module.exports = bookRoute;

Now, sum up all the code and conjugate it in one place so that you can run your backend and propel the CRUD app development forward.

Next, you create and add the following code in the index.js file:

let express = require('express'),
  path = require('path'),
  mongoose = require('mongoose'),
  cors = require('cors'),
  bodyParser = require('body-parser'),
  mongoDb = require('./database/db');
mongoose.Promise = global.Promise;
mongoose.connect(mongoDb.db, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
}).then(() => {
    console.log('Database sucessfully connected ')
  },
  error => {
    console.log('Database error: ' + error)
  }
)
const bookRoute = require('./routes/book.routes')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cors());
// Static directory path
app.use(express.static(path.join(__dirname, 'dist/angular-mean-crud-tutorial')));
// API root
app.use('/api', bookRoute)
// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log('Listening on port ' + port)
})
// 404 Handler
app.use((req, res, next) => {
  next(createError(404));
});
// Base Route
app.get('/', (req, res) => {
  res.send('invaild endpoint');
});
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/angular-mean-crud-tutorial/index.html'));
});
// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

Step 6 – Create Angular Service for REST API Consumption

In the step, you need to visit app/service directory in Angular project and create Book.ts class within.

Then, you add the following code in app/service/Book.ts file:

export class Book {
    _id!: String;
    name!: String;
    price!: String;
    description!: String;
}

Then, you need to execute the command to create a crud service file:

ng g s service/crud

Then, you need to add the below code in app/service/crud.service.ts file:

import { Injectable } from '@angular/core';
import { Book } from './Book';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class CrudService {
  // Node/Express API
  REST_API: string = 'http://localhost:8000/api';
  // Http Header
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }
  // Add
  AddBook(data: Book): Observable<any> {
    let API_URL = `${this.REST_API}/add-book`;
    return this.httpClient.post(API_URL, data)
      .pipe(
        catchError(this.handleError)
      )
  }
  // Get all objects
  GetBooks() {
    return this.httpClient.get(`${this.REST_API}`);
  }
  // Get single object
  GetBook(id:any): Observable<any> {
    let API_URL = `${this.REST_API}/read-book/${id}`;
    return this.httpClient.get(API_URL, { headers: this.httpHeaders })
      .pipe(map((res: any) => {
          return res || {}
        }),
        catchError(this.handleError)
      )
  }
  // Update
  updateBook(id:any, data:any): Observable<any> {
    let API_URL = `${this.REST_API}/update-book/${id}`;
    return this.httpClient.put(API_URL, data, { headers: this.httpHeaders })
      .pipe(
        catchError(this.handleError)
      )
  }
  // Delete
  deleteBook(id:any): Observable<any> {
    let API_URL = `${this.REST_API}/delete-book/${id}`;
    return this.httpClient.delete(API_URL, { headers: this.httpHeaders}).pipe(
        catchError(this.handleError)
      )
  }
  // Error
  handleError(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Handle client error
      errorMessage = error.error.message;
    } else {
      // Handle server error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }
}

Step 7 – Add code In app.component.html

In the step, you need to create HTML and for crud app in Angular. You need to visit src/app/app.component.html and update the below code into the HTML file:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand">Angular 13 CRUD Operations Demo</a>
  <div id="navbarNav" class="collapse navbar-collapse">
    <ul class="navbar-nav ml-auto ">
      <li class="nav-item">
        <a class="nav-link" routerLinkActive="active" routerLink="/books-list">Show Books</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" routerLinkActive="active" routerLink="/add-book">Add Books</a>
      </li>
    </ul>
  </div>
</nav>
<router-outlet></router-outlet>

Step 8 – Create Operation

After that, you can add the code in the add-book.component.ts file:

import { Component, OnInit, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from './../../service/crud.service';
import { FormGroup, FormBuilder } from "@angular/forms";
@Component({
  selector: 'app-add-book',
  templateUrl: './add-book.component.html',
  styleUrls: ['./add-book.component.scss']
})
export class AddBookComponent implements OnInit {
  bookForm: FormGroup;
  
  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private crudService: CrudService
  ) {
    this.bookForm = this.formBuilder.group({
      name: [''],
      price: [''],
      description: ['']
    })
  }
  ngOnInit() { }
  onSubmit(): any {
    this.crudService.AddBook(this.bookForm.value)
    .subscribe(() => {
        console.log('Data added successfully!')
        this.ngZone.run(() => this.router.navigateByUrl('/books-list'))
      }, (err) => {
        console.log(err);
    });
  }
}

Then, you need to add the following code in the add-book.component.html file:

<div class="row justify-content-center mt-5">
    <div class="col-md-4">
        <form [formGroup]="bookForm" (ngSubmit)="onSubmit()">
          <div class="form-group">
            <label>Name</label>
            <input class="form-control" type="text" formControlName="name" required>
          </div>
  
          <div class="form-group">
            <label>Price</label>
            <input class="form-control" type="text" formControlName="price" required>
          </div>
  
          <div class="form-group">
            <label>Description</label>
            <input class="form-control" type="text" formControlName="description" required>
          </div>
  
          <div class="form-group">
            <button class="btn btn-primary btn-block" type="submit">Add Book</button>
          </div>
        </form>
    </div>
  </div>

Next, you add the below code in the books-list.component.ts file:

import { Component, OnInit } from '@angular/core';
import { CrudService } from './../../service/crud.service';
@Component({
  selector: 'app-books-list',
  templateUrl: './books-list.component.html',
  styleUrls: ['./books-list.component.scss']
})
export class BooksListComponent implements OnInit {
  
  Books:any = [];
  constructor(private crudService: CrudService) { }
  ngOnInit(): void {
    this.crudService.GetBooks().subscribe(res => {
      console.log(res)
      this.Books =res;
    });   
  }
  delete(id:any, i:any) {
    console.log(id);
    if(window.confirm('Do you want to go ahead?')) {
      this.crudService.deleteBook(id).subscribe((res) => {
        this.Books.splice(i, 1);
      })
    }
  }
}

Next, you add the below code in the books-list.component.html file:

<div class="container">
  <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h2 class="h2">Books List</h2>
  </div>
  <div class="table-responsive">
    <table class="table table-bordered">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">Name</th>
          <th scope="col">Price</th>
          <th scope="col">Description</th>
          <th class="text-center" scope="col">Action</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let book of Books; let i = index">
          <th scope="row">{{book._id}}</th>
          <td>{{book.name}}</td>
          <td>{{book.price}}</td>
          <td>{{book.description}}</td>
          <td class="text-center">
            <button class="btn btn-sm btn-primary" routerLink="/edit-book/{{book._id}}">Edit</button>
            <button class="btn btn-sm btn-danger" (click)="delete(book._id, i)">Delete</button>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Next, add the below code in the book-detail.component.ts file:

import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CrudService } from './../../service/crud.service';
import { FormGroup, FormBuilder } from "@angular/forms";
@Component({
  selector: 'app-book-detail',
  templateUrl: './book-detail.component.html',
  styleUrls: ['./book-detail.component.scss']
})
export class BookDetailComponent implements OnInit {
  getId: any;
  updateForm: FormGroup;
  
  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private activatedRoute: ActivatedRoute,
    private crudService: CrudService
  ) {
    this.getId = this.activatedRoute.snapshot.paramMap.get('id');
    this.crudService.GetBook(this.getId).subscribe(res => {
      this.updateForm.setValue({
        name: res['name'],
        price: res['price'],
        description: res['description']
      });
    });
    this.updateForm = this.formBuilder.group({
      name: [''],
      price: [''],
      description: ['']
    })
  }
  ngOnInit() { }
  onUpdate(): any {
    this.crudService.updateBook(this.getId, this.updateForm.value)
    .subscribe(() => {
        console.log('Data updated successfully!')
        this.ngZone.run(() => this.router.navigateByUrl('/books-list'))
      }, (err) => {
        console.log(err);
    });
  }
}

Next, add the below code in the book-detail.component.html file:

<div class="row justify-content-center mt-5">
  <div class="col-md-4">
    <form [formGroup]="updateForm" (ngSubmit)="onUpdate()">
      <div class="form-group">
        <label>Name</label>
        <input class="form-control" type="text" formControlName="name" required>
      </div>
      <div class="form-group">
        <label>Price</label>
        <input class="form-control" type="text" formControlName="price" required>
      </div>
      <div class="form-group">
        <label>Description</label>
        <input class="form-control" type="text" formControlName="description" required>
      </div>
      <div class="form-group">
        <button class="btn btn-primary btn-block" type="submit">Update</button>
      </div>
    </form>
  </div>
</div>

For the topic of Angular 13 CRUD application using Node.js, Express.js, and MongoDB. In the tutorial, we introduce how to create a crud app in Angular 13 using Node js and Mongo DB with built REST API.