Objectiv E:: Vehicle Management System
Objectiv E:: Vehicle Management System
1. INTRODUCTION
OBJECTIV
E:
PROBLEM DEFINITION:
1
2. SYSTEM ANALYSIS
EXISITING SYSTEM:
Existing methods on detecting spamming accounts in OSNs,
it is faced with new challenges to detect malicious accounts that participate
in online promotion activities. The existing system doesn’t has token based
authentication while signing in.
Disadvantages
Less Accuracy.
Less Performance.
Proposed System:
We proposed a new solution for privacy preserving user profile.we
have provide that authentication to the user profile through generating the
token.
Advantages
High Accuracy.
High Performance.
System Requirements:
Software Requirements:
Operating System : Windows 10
Application Server : Node js
Front End : HTML, Angular 10, CSS
Scripts : Type Script.
Database : Mongo db
Hardware Requirements:
Processor - Intel i3
RAM - 4GB
Hard Disk - 500 GB
FEASIBILITY STUDY:
The feasibility of the project is analyzed in this phase and business
proposal is put forth with a very general plan for the project and some cost
estimates.
During system analysis the feasibility study of the proposed system is to be
carried out. This is to ensure that the proposed system is not a burden to
the company. For feasibility analysis, some understanding of the major
requirements for the system is essential.
TECHNICAL FEASIBILITY
SOCIAL FEASIBILITY
ECONOMICAL FEASIBILITY
This study is carried out to check the economic impact that the
system will have on the organization. The amount of fund that the company
can pour into the research and development of the system is limited. The
expenditures must be justified. Thus the developed system as well within the
budget and this was achieved because most of the technologies used are
freely available. Only the customized products had to be purchased.
TECHNICAL FEASIBILITY
This study is carried out to check the technical feasibility, that is, the
technical requirements of the system. Any system developed must not have a
high demand on the available technical resources. This will lead to high
demands on the available technical resources. This will lead to high demands
being placed on the client. The developed system must have a modest
requirement, as only minimal or null changes are required for implementing
this system.
SOCIAL FEASIBILITY
Stages in SDLC
Requirement Gathering
Analysis
Designing
Coding
Testing
Analysis Stage
The planning stage establishes a bird's eye view of the intended software
product, and uses this to establish the basic project structure, evaluate
feasibility and risks
associated
with the project, and
describe
appropriate
The design stage takes as its initial input the requirements identified in the
approved requirements document. For each requirement, a set of one or more
design elements will be produced as a result of interviews, workshops, and/or
prototype efforts.
The development stage takes as its primary input the design elements
described in the approved design document. For each design element, a set of
one or more software artifacts will be produced.
During the integration and test stage, the software artifacts, online
help, and
test data are migrated from the development environment to a separate test
environment.
2. Data Store: Here data are stored or referenced by a process in the System.
Data store
3. Data flow: Data flows are pipelines through which packets of information flow.
Label the arrows with the name of the data that moves through it.
4. External Entity: External entities are objects outside the system, with which the
system communicates. External entities are sources and destinations of the system's
inputs and outputs.
Externa
l
Entity
Context (Level 0) DFD
The major objective of a context diagram is to provide a graphical
representation of the whole system. As I stated earlier it consists of all the
system boundaries, all the external entities that interact with the system and
major data flow between the entities in the system.
DATABASE DESIGN
E-R Diagram
Entity
Weak Entity: A weak entity is an entity that must defined by a foreign key
relationship with another entity as it cannot be uniquely identified by its own
attributes alone.
Entity
Key attribute
Multi Valued Attribute: A multi valued attribute can have more than one value.
For example, an employee entity can have multiple skill values.
Multivalued
Derived
Relationships: Relationships illustrate how two entities share information in the
database structure.
UML DIAGRAMS
Unified Modeling Language: Unified Modeling Language (UML) is a
standardized general-purpose modeling language in the field of object-oriented
software engineering.
Fig: UML diagram
UseCase Diagram:
Use case diagrams model the functionality of a system using actors and
use cases. Use cases are services or functions provided by the system to its
users.
System: Draw your system's boundaries using a rectangle that contains use
cases. Place actors outside the system's boundaries.
Use Case: Draw use cases using ovals. Label with ovals with verbs that
represent the system's functions.
Actors: Actors are the users of a system. When one system is the actor of
another system, label the actor system with the actor stereotype.
Relationships: Illustrate relationships between an actor and a use case with a
simple line. For relationships among use cases, use arrows labeled either
"uses" or "extends." A "uses" relationship indicates that one use case is
needed by another in order to perform a task. An "extends" relationship
indicates alternative options under a certain
Sequence Diagram
Component Diagram:
Deployment Diagram
Deployment diagrams depict the physical resources in a system including
nodes, components, and connections.
Collaboration Diagram
A collaboration diagram describes interactions among objects in
terms of sequenced messages. Collaboration diagrams represent a
combination of information taken from class, sequence, and use case
diagrams describing both the static structure and dynamic behavior of a
system. Basic Collaboration Diagram Symbols and Notations.
Activity Diagram
4.1 CODING
Login.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../login.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private ls: LoginService, private router: Router) { }
ngOnInit(): void {
setTimeout(() => {
this.ls.logout();
}, 0);
}
submitform(a) {
if (a.role == "Admin") {
if (a.name = "admin" && (a.password = "admin")) {
this.router.navigate(["/admindashboard"])
}
}
else if (a.role == "Security") {
if (a.name = "security" && (a.password = "security")) {
this.router.navigate(["/securitydashboard"])
}
}
else {
if (a.role == "Employee") {
if (a.name = "employee" && (a.password = "employee")) {
this.router.navigate(["/employeedashboard"])
}
}
}
}
}
Seclog details.comp.ts:
import { Component, OnInit } from '@angular/core';
import { SecurityService } from 'src/app/security.service';
@Component({
selector: 'app-seclogdetails',
templateUrl: './seclogdetails.component.html',
styleUrls: ['./seclogdetails.component.css']
})
export class SeclogdetailsComponent implements OnInit {
constructor(private s: SecurityService) { }
searchterm: any;
lgd:any;
ngOnInit() {
this.s.secudata().subscribe((a) => {
if (a["message"] == "no data found") {
alert('no data found');
}
else {
this.lgd = a["message"];
}
})
}
securityemplog(l) {
this.s.securitydata(l).subscribe((res) => {
alert(res["message"])
this.ngOnInit();
})
}
deleteemp(l) {
this.s.empdel(l).subscribe((res) => {
alert(res["message"])
this.ngOnInit();
})
}
file: File;
fileUpload(filedata) {
this.file = filedata.target.files[0];
}
uploadexcel(data) {
let formdata = new FormData();
formdata.append("uploadfile", this.file, this.file.name);
this.s.setlog(formdata).subscribe((res) => {
if (res["message"] == "uploaded successfully") {
alert(res["message"]);
}
else if (res["err_desc"] == "Corrupted excel file") {
alert(res["err_desc"]);
}
})
}
edata :any=[];
editable(l){
this.edata=l;
console.log(this.edata)
}
updateseclog(g){
console.log(g)
this.s.updatabledata(g).subscribe((res)=>{
this.ngOnInit();
})
}
Employee.comp.ts:
import { Component, OnInit } from '@angular/core';
import { AdminService } from 'src/app/admin.service';
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
constructor(private s: AdminService) { }
details: any;
search:any;
ngOnInit() {
this.s.empreceivingdata().subscribe((res) => {
this.details = res["message"];
console.log(this.details)
})
}
employeedata(c) {
console.log(c);
this.s.senddata(c).subscribe((res) => {
alert(res["message"]);
this.ngOnInit();
})
}
delete(i) {
this.s.deletingdata(i).subscribe((res) => {
this.ngOnInit();
})
}
data :any=[];
edit(a){
this.data=a;
console.log(this.data)
}
update(a){
console.log(a)
this.s.updatedata(a).subscribe((res)=>{
this.ngOnInit();
})
}
Admin.api.js:
const exp = require('express')
const adminapp = exp.Router()
adminapp.use(exp.json())
var dbo;
const mc = require("mongodb").MongoClient;
const dburl = "mongodb://admin:admin@cluster0-shard-00-00-
xvqqz.mongodb.net:27017,cluster0-shard-00-01-xvqqz.mongodb.net:27017,cluster0-
shard-00-02-xvqqz.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority"
mc.connect(dburl, { useNewUrlParser: true, useUnifiedTopology: true }, (err, clientobj)
=> {
if (err) {
console.log("err is", err);
}
else {
dbo = clientobj.db("empdb")
console.log("connected to db");
}
});
adminapp.post('/register', (req, res) => {
console.log(req.body)
dbo.collection("admincollection").findOne({Employeeid: req.body.Employeeid }, (er
r, empobj) => {
if (err) {
console.log("err is occured ", err)
}
else if (empobj == null) {
dbo.collection("admincollection").insertOne(req.body, (err, success) => {
if (err) {
console.log("err is occured", err)
}
else {
res.send({ message: "emp is created successfully" })
}
})
}
if (empobj !== null) {
res.send({ message: "emp is already created" })
}
})
})
module.exports = adminapp;
adminapp.get('/readall', (req, res) => {
console.log(req.body)
dbo.collection("admincollection").find().toArray((err, empArray) => {
if (err) {
console.log("err is occured ", err)
}
else if (empArray == 0) {
alert("emp is not found");
res.send({ message: "no data found" })
}
else {
res.send({ message: empArray })
}
})
})
adminapp.delete('/remove/:i', (req, res) => {
console.log(req.params.i)
dbo.collection("admincollection").deleteOne({Employeeid:req.params.i},(err, delobj)
=> {
if (err) {
console.log("err is occured", err)
}
else {
res.send({message:"deleted successfully"})
}
})
})
adminapp.put('/update',(req,res)=>{
console.log(req.body)
dbo.collection("admincollection").updateOne({Employeeid:req.body.Employeeid},
{$set:{Employeename:req.body.Employeename,
password:req.body.password,vehicleno:req.body.vehicleno,
gender:req.body.gender,
mailid:req.body.mailid,phoneno:req.body.phoneno}},(err,updateobj)=>{
if(err){
console.log("err is occured",err)
}
else{
res.send({message:"update successfully"})
}
})
})
Employee.api.js:
const exp = require('express')
const employeeapp = exp.Router()
employeeapp.use(exp.json())
var dbo;
const mc = require("mongodb").MongoClient;
const dburl = "mongodb://admin:admin@cluster0-shard-00-00-
xvqqz.mongodb.net:27017,cluster0-shard-00-01-xvqqz.mongodb.net:27017,cluster0-
shard-00-02-xvqqz.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority"
mc.connect(dburl, { useNewUrlParser: true, useUnifiedTopology: true }, (err, clientobj)
=> {
if (err) {
console.log("err is", err);
}
else {
dbo = clientobj.db("empdb")
console.log("connected to db");
}
});
module.exports=employeeapp;
employeeapp.post('/register', (req, res) => {
console.log(req.body)
dbo.collection("admincollection").findOne({ Employeeid: req.body.Employeeid }, (e
rr, empobj) => {
if (err) {
console.log("err is occured ", err)
}
else if (empobj == null) {
dbo.collection("admincollection").insertOne(req.body, (err, success) => {
if (err) {
console.log("err is occured", err)
}
else {
res.send({ message: "emp is created successfully" })
}
})
}
if (empobj !== null) {
res.send({ message: "emp is already created" })
}
})
})
///////////////////////////////////////////////////////////////////login/////////////////////////////////////////////////////
///
employeeapp.post("/employeelogin",(req,res)=>{
// console.log(req.body)
dbo.collection("admincollection").findOne({empid:req.body.empid},(err,empobj)=>{
// console.log(empobj)
if(err)
{
console.log("err in employeeusername",err)
}
else if(empobj==null)
{
res.send({message:"invalid username"})
}
else
{
dbo.collection("admincollection").findOne({password:empobj.password},
(err,paswobj)=>{
if(err)
{
console.log("err in employeeusername",err)
}
else if(paswobj==null)
{
res.send({message:"invalid password"})
}
else{
jwt.sign({empid:empobj.empid},"ishh",{expiresIn:60},
(err,signedtoken)=>{
if(err)
{
console.log("err in token is",err)
}
else
{
res.send({message:signedtoken, empid:req.body.empid ,empobj:empobj}
)
}
})
}
})
}
})
})
/////////////////////////////////profile/////////////////////////////////
employeeapp.get("/profile/:empid",(req,res)=>{
dbo.collection("admincollection").findOne({empid:req.params.empid},
(err,empObj)=>{
if(err)
{
console.log("error in profile find",err)
}
else {
res.send({message:empObj})
}
})
})
Screenshot 1:
Screenshot 2:
4.2 TESTING
The purpose of testing is to discover errors. Testing is the process
of trying to discover every conceivable fault or weakness in a work
product. It provides a way to check the functionality of components,
subassemblies, assemblies and/or a finished product It is the process of
exercising software with the intent of ensuring that theSoftware system
meets its requirements and user expectations and does not fail in an
unacceptable manner. There are various types of test. Each test type
addresses a specific testing requirement.
In order to make sure that the system does not have errors, the different
levels of testing strategies that are applied at differing phases of software
development are:
Unit Testing:
Unit testing is usually conducted as part of a combined code and unit test
phase of the software lifecycle, although it is not uncommon for coding
and unit testing to be conducted as two distinct phases.
Black Box Testing is testing the software without any knowledge of the inner
workings, structure or language of the module being tested. Black box tests,
as most other kinds of tests, must be written from a definitive source
document, such as specification or requirements document, such as
specification or requirements document. It is a testing in which the software
under test is treated, as a black box
.you cannot “see” into it. The test provides inputs and responds to outputs
without considering how the software works.
Integrating Testing:
Test Results: All the test cases mentioned above passed successfully. No defects
encountered.
System Testing:
System testing ensures that the entire integrated software system meets
requirements. It tests a configuration to ensure known and predictable results.
An example of system testing is the configuration oriented system integration
test.
System testing is based on process descriptions and flows, emphasizing pre-
driven process links and integration points.
Acceptance Testing:
Test Results: All the test cases mentioned above passed successfully. No
defects encountered.
Test Approach:
Field testing will be performed manually and functional tests will be written
in detail.
Test objectives
All field entries must work properly.
Pages must be activated from the identified link.
This type of testing starts from upper level modules. Since the detailed
activities usually performed in the lower level routines are not provided stubs
are written. A stub is a module shell called by upper level module and that
when reached properly will return a message to the calling module indicating
that proper interaction occurred. No attempt is made to verify the correctness
of the lower level module.
5. Validation: The system has been tested and implemented successfully and thus
ensured that all the requirements as listed in the software requirements
specification are completely ful-filled. In case of erroneous input
corresponding error
messages are displayed.
FUTURE SCOPE
This system helps the end users of the system in taking the details of checkin
and checkout status of vehicles of employess.
It is not possible to develop a system that makes all the requirements of the
user. User requirements keep changing as the system is being used. Some of the
future enhancements that can be done to this system are:
6.Appendices
TypeScript:
Functions are the building blocks of readable, maintainable, and reusable code. A function is a set
of statements to perform a specific task. Functions organize the program into logical blocks of
code. Once defined, functions may be called to access code. This makes the code reusable.
Moreover, functions make it easy to read and maintain the program’s code.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
1. Defining a Function
A function definition specifies what and how a specific task would be done.
2. Calling a Function
A function must be called so as to execute it.
3. Returning Functions
Functions may also return value along with control, back to the caller.
4. Parameterized Function
Parameters are a mechanism to pass values to functions.
Optional Parameters
Optional parameters can be used when arguments need not be compulsorily passed for a
function’s execution. A parameter can be marked optional by appending a question mark to its
name. The optional parameter should be set as the last argument in a function. The syntax to
declare a function with optional parameter is as given below −
function function_name (param1[:type], param2[:type], param3[:type])
Example: Optional Parameters
function disp_details(id:number,name:string,mail_id?:string) {
console.log("ID:", id);
console.log("Name",name);
if(mail_id!=undefined)
console.log("Email Id",mail_id);
}
disp_details(123,"John");
disp_details(111,"mary","[email protected]");
The above example declares a parameterized function. Here, the third parameter, i.e.,
mail_id is an optional parameter.
If an optional parameter is not passed a value during the function call, the parameter’s
value is set to undefined.
The function prints the value of mail_id only if the argument is passed a value.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
function disp_details(id, name, mail_id) {
console.log("ID:", id);
console.log("Name", name);
if (mail_id != undefined)
console.log("Email Id", mail_id);
}
disp_details(123, "John");
disp_details(111, "mary", "[email protected]");
The above code will produce the following output −
ID:123
Name John
ID: 111
Name mary
Email Id [email protected]
Rest Parameters
Rest parameters are similar to variable arguments in Java. Rest parameters don’t restrict the
number of values that you can pass to a function. However, the values passed must all be of the
same type. In other words, rest parameters act as placeholders for multiple arguments of the same
type.
To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest
parameter should come before the rest parameter.
Example: Rest Parameters
function addNumbers(...nums:number[]) {
var i;
var sum:number = 0;
for(i = 0;i<nums.length;i++) {
sum = sum + nums[i];
}
console.log("sum of the numbers",sum)
}
addNumbers(1,2,3)
addNumbers(10,10,10,10,10)
The function addNumbers() declaration, accepts a rest parameter nums. The rest
parameter’s data type must be set to an array. Moreover, a function can have at the most
one rest parameter.
The function is invoked twice, by passing three and six values, respectively.
The for loop iterates through the argument list, passed to the function and calculates their
sum.
On compiling, it will generate following JavaScript code −
function addNumbers() {
var nums = [];
for (var _i = 0; _i < arguments.length; _i++) {
nums[_i - 0] = arguments[_i];
}
var i;
var sum = 0;
Anonymous Function
Functions that are not bound to an identifier (function name) are called as anonymous functions.
These functions are dynamically declared at runtime. Anonymous functions can accept inputs and
return outputs, just as standard functions do. An anonymous function is usually not accessible
after its initial creation.
Variables can be assigned an anonymous function. Such an expression is called a function
expression.
Syntax
var res = function( [arguments] ) { ... }
Example ─ A Simple Anonymous function
var msg = function() {
return "hello world";
}
console.log(msg())
On compiling, it will generate the same code in JavaScript.
It will produce the following output −
hello world
Example ─ Anonymous function with parameters
var res = function(a:number,b:number) {
return a*b;
};
console.log(res(12,2))
The anonymous function returns the product of the values passed to it.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var res = function (a, b) {
return a * b;
};
console.log(res(12, 2));
The output of the above code is as follows −
24
Function Expression and Function Declaration ─ Are they synonymous?
Function expression and function declaration are not synonymous. Unlike a function expression, a
function declaration is bound by the function name.
The fundamental difference between the two is that, function declarations are parsed before their
execution. On the other hand, function expressions are parsed only when the script engine
encounters it during execution.
When the JavaScript parser sees a function in the main code flow, it assumes Function
Declaration. When a function comes as a part of a statement, it is a Function Expression.
//code block
}
Example: Lambda statement
var foo = (x:number)=> {
x = 10 + x
console.log(x)
}
foo(100)
The function’s reference is returned and stored in the variable foo.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var foo = function (x) {
x = 10 + x;
console.log(x);
};
foo(100);
The output of the above program is as follows −
110
Syntactic Variations
Parameter type Inference
It is not mandatory to specify the data type of a parameter. In such a case the data type of the
parameter is any. Let us take a look at the following code snippet −
var func = (x)=> {
if(typeof x=="number") {
console.log(x+" is numeric")
} else if(typeof x=="string") {
console.log(x+" is a string")
}
}
func(12)
func("Tom")
On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var func = function (x) {
if (typeof x == "number") {
console.log(x + " is numeric");
} else if (typeof x == "string") {
console.log(x + " is a string");
}
};
func(12);
func("Tom");
Its output is as follows −
12 is numeric
Tom is a string
Optional parentheses for a single parameter
var display = x=> {
console.log("The function got "+x)
}
display(12)
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var display = function (x) {
console.log("The function got " + x);
};
display(12);
Its output is as follows −
The function got 12
Optional braces for a single statement, Empty parentheses for no parameter
The following example shows these two Syntactic variations.
var disp =()=> {
console.log("Function invoked");
}
disp();
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var disp = function () {
console.log("Function invoked");
};
disp();
Its output is as follows −
Function invoked
Function Overloads
Functions have the capability to operate differently on the basis of the input provided to them. In
other words, a program can have multiple methods with the same name with different
implementation. This mechanism is termed as Function Overloading. TypeScript provides support
for function overloading.
To overload a function in TypeScript, you need to follow the steps given below −
Step 1 − Declare multiple functions with the same name but different function signature. Function
signature includes the following.
The data type of the parameter
function disp(string):void;
function disp(number):void;
The number of parameters
function disp(n1:number):void;
function disp(x:number,y:number):void;
The sequence of parameters
function disp(n1:number,s1:string):void;
function disp(s:string,n:number):void;
Note − The function signature doesn’t include the function’s return type.
Step 2 − The declaration must be followed by the function definition. The parameter types should
be set to any if the parameter types differ during overload. Additionally, for case b explained
above, you may consider marking one or more parameters as optional during the function
definition.
Step 3 − Finally, you must invoke the function to make it functional.
Example
Let us now take a look at the following example code −
function disp(s1:string):void;
function disp(n1:number,s1:string):void;
function disp(x:any,y?:any):void {
console.log(x);
console.log(y);
}
disp("abc")
disp(1,"xyz");
The first two lines depict the function overload declaration. The function has two overloads
−
o Function that accepts a single string parameter.
o Function that accepts two values of type number and string respectively.
The third line defines the function. The data type of the parameters are set to any.
Moreover, the second parameter is optional here.
The overloaded function is invoked by the last two statements.
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
function disp(x, y) {
console.log(x);
console.log(y);
}
disp("abc");
disp(1, "xyz");
The above code will produce the following output −
abc
1
xyz
Strings:
The String object lets you work with a series of characters. It wraps the string primitive data type
with a number of helper methods.
Syntax
var var_name = new String(string);
A list of the methods available in String object along with their description is given below −
1. Constructor
2. Length
Returns the length of the string.
3. Prototype
The prototype property allows you to add properties and methods to an object.
String Methods
A list of the methods available in String object along with their description is given below −
1. charAt()
2. charCodeAt()
Returns a number indicating the Unicode value of the character at the given index.
3. concat()
Combines the text of two strings and returns a new string.
4. indexOf()
Returns the index within the calling String object of the first occurrence of the specified
value, or -1 if not found.
5. lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified
value, or -1 if not found.
6. localeCompare()
Returns a number indicating whether a reference string comes before or after or is the same
as the given string in sort order.
7.
match()
Used to match a regular expression against a string.
8. replace()
Used to find a match between a regular expression and a string, and to replace the matched
substring with a new substring.
9. search()
Executes the search for a match between a regular expression and a specified string.
10. slice()
Extracts a section of a string and returns a new string.
11. split()
Splits a String object into an array of strings by separating the string into substrings.
12. substr()
Returns the characters in a string beginning at the specified location through the specified
number of characters.
13. substring()
Returns the characters in a string between two indexes into the string.
14. toLocaleLowerCase()
The characters within a string are converted to lower case while respecting the current
locale.
15. toLocaleUpperCase()
The characters within a string are converted to upper case while respecting the current
locale.
16. toLowerCase()
Returns the calling string value converted to lower case.
17. toString()
Returns a string representing the specified object.
18. toUpperCase()
Returns the calling string value converted to uppercase.
19. valueOf()
Returns the primitive value of the specified object.
Features of an Array
Here is a list of the features of an array −
An array declaration allocates sequential memory blocks.
Arrays are static. This means that an array once initialized cannot be resized.
Each memory block represents an array element.
Array elements are identified by a unique integer called as the subscript / index of the
element.
Like variables, arrays too, should be declared before they are used. Use the var keyword to
declare an array.
Array initialization refers to populating the array elements.
Array element values can be updated or modified but cannot be deleted.
for(var i = 0;i<arr_names.length;i++;) {
arr_names[i] = i * 2
console.log(arr_names[i])
}
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var arr_names = new Array(4);
for(var i = 0;i<names.length;i++) {
console.log(names[i])
}
On compiling, it will generate following JavaScript code −
//Generated by typescript 1.8.10
var names = new Array("Mary", "Tom", "Jack", "Jill");
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
}
Its output is as follows −
Mary
Tom
Jack
Jill
Array Methods
A list of the methods of the Array object along with their description is given below.
1. concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
2. every()
Returns true if every element in this array satisfies the provided testing function.
3. filter()
Creates a new array with all of the elements of this array for which the provided filtering
function returns true.
4. forEach()
Calls a function for each element in the array.
5. indexOf()
Returns the first (least) index of an element within the array equal to the specified value, or
-1 if none is found.
6. join()
Joins all elements of an array into a string.
7. lastIndexOf()
Returns the last (greatest) index of an element within the array equal to the specified value,
or -1 if none is found.
8. map()
Creates a new array with the results of calling a provided function on every element in this
array.
9. pop()
Removes the last element from an array and returns that element.
10. push()
Adds one or more elements to the end of an array and returns the new length of the array.
11. reduce()
Apply a function simultaneously against two values of the array (from left-to-right) as to
reduce it to a single value.
12. reduceRight()
Apply a function simultaneously against two values of the array (from right-to-left) as to
reduce it to a single value.
13. reverse()
Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.
14. shift()
Removes the first element from an array and returns that element.
15. slice()
Extracts a section of an array and returns a new array.
16. some()
Returns true if at least one element in this array satisfies the provided testing function.
17. sort()
Sorts the elements of an array.
18. splice()
Adds and/or removes elements from an array.
19. toString()
Returns a string representing the array and its elements.
20. unshift()
Adds one or more elements to the front of an array and returns the new length of the array.
Array Destructuring
Refers to breaking up the structure of an entity. TypeScript supports destructuring when used in
the context of an array.
Example
var arr:number[] = [12,13]
var[x,y] = arr
console.log(x)
console.log(y)
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var arr = [12, 13];
var x = arr[0], y = arr[1];
console.log(x);
console.log(y);
Its output is as follows −
12
13
Array Traversal using for…in loop
One can use the for…in loop to traverse through an array.
var j:any;
var nums:number[] = [1001,1002,1003,1004]
for(j in nums) {
console.log(nums[j])
}
The loop performs an index based array traversal.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var j;
var nums = [1001, 1002, 1003, 1004];
for (j in nums) {
console.log(nums[j]);
}
The output of the above code is given below −
1001
1002
1003
1004
Arrays in TypeScript
TypeScript supports the following concepts in arrays −
1. Multi-dimensional arrays
TypeScript supports multidimensional arrays. The simplest form of the multidimensional
array is the twodimensional array.
console.log(tup[0])
console.log(tup[1])
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
12
23
Tuple Operations
Tuples in TypeScript supports various operations like pushing a new item, removing an item from
the tuple, etc.
Example
var mytuple = [10,"Hello","World","typeScript"];
console.log("Items before push "+mytuple.length) // returns the tuple size
Angular
Angular 8 was a release that spanned the entire platform, including the framework, Angular
Material, and the CLI. This release improved application startup time on modern browsers. Also it
changed the route configurations to use dynamic imports in favour of lazy loading.
Angular 9 was very expected by the community because it introduced the Ivy compiler and
runtime. Ivy is the name for Angular's next-generation compilation and rendering pipeline. With
this release, the new compiler and runtime instructions are used by default instead of the older
compiler and runtime, known as View Engine.
Components are basically classes that interact with the .html file of the component, which gets
displayed on the browser. We have seen the file structure in one of our previous chapters. The file
structure has the app component and it consists of the following files −
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
The above files were created by default when we created new project using the angular-cli
command.
If you open up the app.module.ts file, it has some libraries which are imported and also a
declarative which is assigned the appcomponent as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
@NgModule({
declarations: [
AppComponent,
NewCmpComponent // here it is added in declarations and will behave as a child component
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent] //for bootstrap the AppComponent the main app component is given.
})
@Component({
// this is a declarator which starts with @ sign. The component word marked in bold needs to be the
same.
selector: 'app-new-cmp', //
templateUrl: './new-cmp.component.html',
// reference to the html file created in the new component.
styleUrls: ['./new-cmp.component.css'] // reference to the style file.
})
<body>
<app-root></app-root>
</body>
</html>
The above is the normal html file and we do not see anything that is printed in the browser. Take a
look at the tag in the body section.
<app-root></app-root>
This is the root tag created by the Angular by default. This tag has the reference in
the main.ts file.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
AppModule is imported from the app of the main parent module, and the same is given to the
bootstrap Module, which makes the appmodule load.
Let us now see the app.module.ts file −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
@NgModule({
declarations: [
AppComponent,
NewCmpComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
<app-new-cmp></app-new-cmp>
When the <app-new-cmp></app-new-cmp> tag is added, all that is present in the .html file of
the new component created will get displayed on the browser along with the parent component
data.
Let us see the new component .html file and the new-cmp.component.ts file.
new-cmp.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
<p>
new-cmp works!
</p>
Now since we have included the <app-new-cmp></app-new-cmp> selector in the app.
component .html which is the .html of the parent component, the content present in the new
component .html file (new-cmp.component.html) gets displayed on the browser as follows −
Similarly, we can create components and link the same using the selector in
the app.component.html file as per our requirements.
MODULE:
Module in Angular refers to a place where you can group the components, directives, pipes, and
services, which are related to the application.
In case you are developing a website, the header, footer, left, center and the right section become
part of a module.
To define module, we can use the NgModule. When you create a new project using the Angular –
cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows
−
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The NgModule needs to be imported as follows −
import { NgModule } from '@angular/core';
The structure for the ngmodule is as shown below −
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
It starts with @NgModule and contains an object which has declarations, import s, providers and
bootstrap.
Declaration
It is an array of components created. If any new component gets created, it will be imported first
and the reference will be included in declarations as shown below −
declarations: [
AppComponent,
NewCmpComponent
]
Import
It is an array of modules required to be used in the application. It can also be used by the
components in the Declaration array. For example, right now in the @NgModule we see the
Browser Module imported. In case your application needs forms, you can include the module as
follows −
import { FormsModule } from '@angular/forms';
The import in the @NgModule will be like the following −
imports: [
BrowserModule,
FormsModule
]
Providers
This will include the services created.
Bootstrap
This includes the main app component for starting the execution.
Data binding:
Data Binding is available right from AngularJS, Angular 2 and is now available in Angular 4 as
well. We use curly braces for data binding - {{}}; this process is called interpolation. We have
already seen in our previous examples how we declared the value to the variable title and the same
is printed in the browser.
The variable in the app.component.html file is referred as {{title}} and the value of title is
initialized in the app.component.ts file and in app.component.html, the value is displayed.
Let us now create a dropdown of months in the browser. To do that , we have created an array of
months in app.component.ts as follows −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
// declared array of months.
months = ["January", "Feburary", "March", "April", "May",
"June", "July", "August", "September",
"October", "November", "December"];
}
The month’s array that is shown above is to be displayed in a dropdown in the browser. For this,
we will use the following line of code −
<!--The content below is only a placeholder and can be replaced. -->
<div style="text-align:center">
<h1>
Welcome to {{title}}.
</h1>
</div>
<div> Months :
<select>
<option *ngFor="let i of months">{{i}}</option>
</select>
</div>
We have created the normal select tag with option. In option, we have used the for loop. The for
loop is used to iterate over the months’ array, which in turn will create the option tag with the
value present in the months.
The syntax for in Angular is *ngFor = “let I of months” and to get the value of months we are
displaying it in {{i}}.
The two curly brackets help with data binding. You declare the variables in
your app.component.ts file and the same will be replaced using the curly brackets.
Let us see the output of the above month’s array in the browser
The variable that is set in the app.component.ts can be bound with
the app.component.html using the curly brackets; for example, {{}}.
Let us now display the data in the browser based on condition. Here, we have added a variable
and assigned the value as true. Using the if statement, we can hide/show the content to be
displayed.
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
<div> Months :
<select>
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable">Condition is valid.</span>
//over here based on if condition the text condition is valid is displayed.
If the value of isavailable is set to false it will not display the text.
</div>
Output
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
<div> Months :
<select>
<option *ngFor="let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf="isavailable; else condition1">Condition is valid.</span>
<ng-template #condition1>Condition is invalid</ng-template>
</div>
If is used with the else condition and the variable used is condition1. The same is assigned as
an id to the ng-template, and when the available variable is set to false the text Condition is
invalid is displayed.
The following screenshot shows the display in the browser.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
<div> Months :
<select>
<option *ngFor="let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf="isavailable; then condition1 else condition2">Condition is valid.</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
If the variable is true, then condition1, else condition2. Now, two templates are created with
id #condition1 and #condition2.
The display in the browser is as follows −
Event binding:
In this chapter, we will discuss how Event Binding works in Angular 4. When a user interacts
with an application in the form of a keyboard movement, a mouse click, or a mouseover, it
generates an event. These events need to be handled to perform some kind of action. This is where
event binding comes into picture.
Let us consider an example to understand this better.
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1>
Welcome to {{title}}.
</h1>
</div>
<div> Months :
<select>
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable; then condition1 else condition2">
Condition is valid.
</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
<button (click)="myClickFunction($event)">
Click Me
</button>
In the app.component.html file, we have defined a button and added a function to it using the
click event.
Following is the syntax to define a button and add a function to it.
(click)="myClickFunction($event)"
The function is defined in the .ts file: app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
<div> Months :
<select (change) = "changemonths($event)">
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable; then condition1 else condition2">
Condition is valid.
</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Let us add an alert message in app.component.ts when the value from the dropdown is changed
as shown below −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
isavailable = true;
myClickFunction(event) {
//just added console.log which will display the event details in browser
on click of the button.
alert("Button is clicked");
console.log(event);
}
changemonths(event) {
alert("Changed month from the Dropdown");
}
}
When the value in dropdown is changed, a dialog box will appear and the following message will
be displayed - “Changed month from the Dropdown”.
Directives:
Directives in Angular is a js class, which is declared as @directive. We have 3 directives in
Angular. The directives are listed below −
Component Directives
These form the main class having details of how the component should be processed, instantiated
and used at runtime.
Structural Directives
A structure directive basically deals with manipulating the dom elements. Structural directives
have a * sign before the directive. For example, *ngIf and *ngFor.
Attribute Directives
Attribute directives deal with changing the look and behavior of the dom element. You can create
your own directives as shown below.
e.g
ng g directive changeText
This is how it appears in the command line
C:\projectA4\Angular 4-app>ng g directive changeText
installing directive
create src\app\change-text.directive.spec.ts
create src\app\change-text.directive.ts
update src\app\app.module.ts
The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and
the app.module.ts file is updated.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
Pipes:
Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4.
The | character is used to transform data. Following is the syntax for the same
{{ Welcome to Angular 4 | lowercase}}
It takes integers, strings, arrays, and date as input separated with | to be converted in the format as
required and display the same in the browser.
Let us consider a few examples using pipes.
Here, we want to display the text given to uppercase. This can be done using pipes as follows −
In the app.component.ts file, we have defined the title variable −
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Angular 4 provides some built-in pipes. The pipes are listed below −
Lowercasepipe
Uppercasepipe
Datepipe
Currencypipe
Jsonpipe
Percentpipe
Decimalpipe
Slicepipe
We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes
work.
The following line of code will help us define the required variables in app.component.ts file −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
<h1>Lowercase Pipe</h1>
<b>{{title | lowercase}}</b>
<h1>Currency Pipe</h1>
<b>{{6589.23 | currency:"USD"}}</b><br/>
<b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.
<h1>Date pipe</h1>
<b>{{todaydate | date:'d/M/y'}}</b><br/>
<b>{{todaydate | date:'shortTime'}}</b>
<h1>Decimal Pipe</h1>
<b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be
displayed.
</div>
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify
the path of the file. It also has to be included in the declarations as shown above.
Let us now see the call made to the sqrt pipe in the app.component.html file.
<h1>Custom Pipe</h1>
<b>Square root of 25 is: {{25 | sqrt}}</b>
<br/>
<b>Square root of 729 is: {{729 | sqrt}}</b>
The output looks as follows −
Routing basically means navigating between pages. You have seen many sites with links that
direct you to a new page. This can be achieved using routing. Here the pages that we are referring
to will be in the form of components. We have already seen how to create a component. Let us
now create a component and see how to use routing with it.
In the main parent component app.module.ts, we have to now include the router module as
shown below −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
<p>
new-cmp works!
</p>
Now, we need the above content from the html file to be displayed whenever required or clicked
from the main module. For this, we need to add the router details in the app.component.html.
<h1>Custom Pipe</h1>
<b>Square root of 25 is: {{25 | sqrt}}</b><br/>
<b>Square root of 729 is: {{729 | sqrt}}</b>
<br />
<br />
<br />
<a routerLink = "new-cmp">New component</a>
<br />
<br/>
<router-outlet></router-outlet>
In the above code, we have created the anchor link tag and given routerLink as “new-cmp”. This
is referred in app.module.ts as the path.
When a user clicks new component, the page should display the content. For this, we need the
following tag - <router-outlet> </router-outlet>.
The above tag ensures that the content in the new-cmp.component.html will be displayed on the
page when a user clicks new component.
Let us now see how the output is displayed on the browser.
When a user clicks New component, you will see the following in the browser.
The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the
original url, which is the path given in the app.module.ts and the router-link in
the app.component.html.
When a user clicks New component, the page is not refreshed and the contents are shown to the
user without any reloading. Only a particular piece of the site code will be reloaded when clicked.
This feature helps when we have heavy content on the page and needs to be loaded based on the
user interaction. The feature also gives a good user experience as the page is not reloaded.
Services:
We might come across a situation where we need some code to be used everywhere on the page. It
can be for data connection that needs to be shared across components, etc. Services help us
achieve that. With services, we can access methods and properties across other components in the
entire project.
To create a service, we need to make use of the command line. The command for the same is −
C:\projectA4\Angular 4-app>ng g service myservice
installing service
create src\app\myservice.service.spec.ts
create src\app\myservice.service.ts
WARNING Service is generated but not provided, it must be provided to be used
C:\projectA4\Angular 4-app>
The files are created in the app folder as follows −
@Injectable()
export class MyserviceService {
constructor() { }
}
Here, the Injectable module is imported from the @angular/core. It contains
the @Injectable method and a class called MyserviceService. We will create our service
function in this class.
Before creating a new service, we need to include the service created in the main
parent app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
If you change the property of the service in any component, the same is changed in other
components too. Let us now see how this works.
We will define one variable in the service and use it in the parent and the new component. We
will again change the property in the parent component and will see if the same is changed in the
new component or not.
In myservice.service.ts, we have created a property and used the same in other parent and new
component.
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
serviceproperty = "Service Created";
constructor() { }
showTodayDate() {
let ndate = new Date();
return ndate;
}
}
Let us now use the serviceproperty variable in other components. In app.component.ts, we are
accessing the variable as follows −
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
MongoDB is a cross-platform, document oriented database that provides, high performance, high
availability, and easy scalability. MongoDB works on concept of collection and document.
Database
Database is a physical container for collections. Each database gets its own set of files on the file
system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents within
a collection can have different fields. Typically, all documents in a collection are of similar or
related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
mysqld/Oracle mongod
mysql/sqlplus mongo
Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can
provide _id while inserting the document. If you don’t provide then MongoDB provides a unique
id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for
machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes are simple
incremental VALUE.
table. Advantages: