In this tutorial, we will create a MEAN Stack Application. We will cover a detailed tutorial about MEAN Stack in the future. But, right now, use the CRUD application, and we will build it.
Prerequisites
If you are new to Angular, please check out these tutorials.
Angular CRUD
First, we need to install the Frontend Framework. So Let’s start with Installing the Angular Framework.
Then we will set up the routing and then set the API endpoint to request the server, query the database according to request, and display the information according to it.
Step 1: Install Angular via CLI.
You need to set up a dev environment before you can do anything.
Install Node.js® and npm if not already on your machine.
npm install -g @angular/cli
Step 2. Create a new project.
Type the following command. It will create the folder structure and also install the remaining dependencies.
ng new ng5crud
Step 3: Make three components of the application.
Create one directory inside the src >> app folder called components.
Go to the root of the folder and in the console and hit the following command.
ng g c index ng g c create ng g c edit
We have created three components. Each component will do its job. Here we are establishing the single responsibility principle for every component.
It makes a separate folder inside the src >> app directory. We need to move all these three folders inside the components folder.
Also, we need to change the app.module.ts file, to write the correct path of the imported components. By default, it’s an app directory.
The Angular Router
enables navigation from one view to the next as users perform application tasks.
First, we need to import the routing modules inside our app.module.ts file.
// app.module.ts import { RouterModule } from '@angular/router'; imports: [ BrowserModule, RouterModule ],
Configuration
When we created the components, its default path was different, and now we have moved to the components, so its path is different. So, first, we need to change that path in the app.module.ts file.
Okay, now we need to configure the routes. So make one file
inside the app directory called routerConfig.ts file.
Write the following code in it.
// routerConfig.ts import { Routes } from '@angular/router'; import { CreateComponent } from './components/create/create.component'; import { EditComponent } from './components/edit/edit.component'; import { IndexComponent } from './components/index/index.component'; export const appRoutes: Routes = [ { path: 'create', component: CreateComponent }, { path: 'edit/:id', component: EditComponent }, { path: 'index', component: IndexComponent } ];
We defined one array, and inside that array, we registered the different routes with their components. Then, finally, we exported it.
Now, import this object inside app.module.ts and register the module.
// app.module.ts import { appRoutes } from './routerConfig'; imports: [ BrowserModule, RouterModule.forRoot(appRoutes) ],
Step 5: Define the Router outlet.
In the app.component.html file, write the following code.
<div style="text-align:center"> <h1> Welcome to {{title}}!! </h1> <nav> <a routerLink="create" routerLinkActive="active">Add coins</a> </nav> <router-outlet></router-outlet> </div>
Also, we need to change the title attribute.
// app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Welcome to crypto world'; }
Step 6: Add Bootstrap CSS.
Download the bootstrap from its original docs and paste the CSS and JS folders inside the src >> assets folder.
In the src >> index.html file, add the bootstrap css file.
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
Also, change the app.component.html outlook due to bootstrap classes.
<nav class="navbar navbar-default"> <div class="container-fluid"> <ul class="nav navbar-nav"> <li class="active"> <a routerLink="create" routerLinkActive="active"> Add coins </a> </li> </ul> </div> </nav> <div class="container"> <router-outlet></router-outlet> </div>
Step 7: Make a form in the create a component file.
First, our create.component.ts file looks like this.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { title = 'Add Coin'; constructor() { } ngOnInit() { } }
And then, we need to make the create.component.html form design.
<div class="panel panel-primary"> <div class="panel-heading"> {{ title }} </div> <div class="panel-body"> <form> <div class="form-group"> <label class="col-md-4">Coin Name</label> <input type="text" class="form-control" name="coin_name"/> </div> <div class="form-group"> <label class="col-md-4">Coin Price</label> <input type="text" class="form-control" name="coin_price"/> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Add</button> </div> </form> </div> </div>
Now, head over to this. http://localhost:4200/create . It looks like this.
Step 8: Configure HttpClientModule.
Go to the app.module.ts file. Include the HttpClientModule in it.
import {HttpClientModule} from '@angular/common/http'; imports: [ BrowserModule, RouterModule.forRoot(appRoutes), HttpClientModule ],
Step 9: Create services to send http requests.
Type the following command in your terminal.
ng g service coin
It will create the following classes.
- coin.service.ts
- coin.service.spec.ts
Now, import the service file into the app.module.ts file.
import { CoinService } from './coin.service'; providers: [CoinService]
Step 10: Configure Node.js MongoDB backend.
The next step would be to create Node.js and Express backend to store the data. Create one file in the project root called server.js
We need to install the express framework and other dependencies via NPM, so let us do it first.
npm install --save express body-parser cors mongoose nodemon
Switch to the newly created server.js file and enter the following code.
// server.js var express = require('express'), path = require('path'), bodyParser = require('body-parser'), cors = require('cors'), mongoose = require('mongoose'); const app = express(); var port = process.env.PORT || 4000; var server = app.listen(function(){ console.log('Listening on port ' + port); });
Next, we must create the MongoDB database and connect it with our express application.
Note: You must have installed the MongoDB database on your server or locally; otherwise, you need to download it and start the MongoDB server.
Create one config folder inside the project root. In that, create one file called DB.js.
// DB.js module.exports = { DB: 'mongodb://localhost:27017/angularcrud' };
Import this file into our server.js file and use mongoose to set up a database connection with MongoDB. You need to copy the whole server.js file; I am about to show it so that nothing will be left and lead us to an error.
// server.js const express = require('express'), path = require('path'), bodyParser = require('body-parser'), cors = require('cors'), mongoose = require('mongoose'), config = require('./config/DB'); mongoose.Promise = global.Promise; mongoose.connect(config.DB).then( () => {console.log('Database is connected') }, err => { console.log('Can not connect to the database'+ err)} ); const app = express(); app.use(bodyParser.json()); app.use(cors()); const port = process.env.PORT || 4000; const server = app.listen(port, function(){ console.log('Listening on port ' + port); });
Step 11: Create Express routes for our application.
We need to create two folders in a root called expressRoutes and models.
In the models folder, create one model called Coin.js.
var mongoose = require('mongoose'); var Schema = mongoose.Schema; // Define collection and schema for Items var Coin = new Schema({ name: { type: String }, price: { type: Number } },{ collection: 'coins' }); module.exports = mongoose.model('Coin', Coin);
In the expressRouter folder, create one file called coinRoutes.js.
// coinRoutes.js var express = require('express'); var app = express(); var coinRoutes = express.Router(); // Require Item model in our routes module var Coin = require('../models/Coin'); // Defined store route coinRoutes.route('/add').post(function (req, res) { var coin = new Coin(req.body); coin.save() .then(item => { res.status(200).json({'coin': 'Coin added successfully'}); }) .catch(err => { res.status(400).send("unable to save to database"); }); }); // Defined get data(index or listing) route coinRoutes.route('/').get(function (req, res) { Coin.find(function (err, coins){ if(err){ console.log(err); } else { res.json(coins); } }); }); // Defined edit route coinRoutes.route('/edit/:id').get(function (req, res) { var id = req.params.id; Coin.findById(id, function (err, coin){ res.json(coin); }); }); // Defined update route coinRoutes.route('/update/:id').post(function (req, res) { Coin.findById(req.params.id, function(err, coin) { if (!coin) return next(new Error('Could not load Document')); else { coin.name = req.body.name; coin.price = req.body.price; coin.save().then(coin => { res.json('Update complete'); }) .catch(err => { res.status(400).send("unable to update the database"); }); } }); }); // Defined delete | remove | destroy route coinRoutes.route('/delete/:id').get(function (req, res) { Coin.findByIdAndRemove({_id: req.params.id}, function(err, coin){ if(err) res.json(err); else res.json('Successfully removed'); }); }); module.exports = coinRoutes;
Here, I have defined all the routes related to the CRUD application. This file will be included in our server.js file.
// server.js coinRoutes = require('./expressRoutes/coinRoutes'); app.use('/coins', coinRoutes);
Step 12: Insert the value in MongoDB.
From the front end side, we need to set up HttpClientModule and fire up the HTTP Post call to the NodeJS server.
// server.js const express = require('express'), path = require('path'), bodyParser = require('body-parser'), cors = require('cors'), mongoose = require('mongoose'), config = require('./config/DB'), coinRoutes = require('./expressRoutes/coinRoutes'); mongoose.Promise = global.Promise; mongoose.connect(config.DB).then( () => {console.log('Database is connected') }, err => { console.log('Can not connect to the database'+ err)} ); const app = express(); app.use(bodyParser.json()); app.use(cors()); const port = process.env.PORT || 4000; app.use('/coins', coinRoutes); const server = app.listen(port, function(){ console.log('Listening on port ' + port); });
We need to include the ReactiveFormsModule in the app.module.ts file.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { IndexComponent } from './components/index/index.component'; import { CreateComponent } from './components/create/create.component'; import { EditComponent } from './components/edit/edit.component'; import { appRoutes } from './routerConfig'; import { CoinService } from './coin.service'; @NgModule({ declarations: [ AppComponent, IndexComponent, CreateComponent, EditComponent ], imports: [ BrowserModule, RouterModule.forRoot(appRoutes), HttpClientModule, ReactiveFormsModule ], providers: [CoinService], bootstrap: [AppComponent] }) export class AppModule { }
Then, we validate the forms. So first, write the form HTML in the create.component.html.
<div class="panel panel-primary"> <div class="panel-heading"> {{ title }} </div> <div class="panel-body"> <form [formGroup]="angForm" novalidate> <div class="form-group"> <label class="col-md-4">Coin Name</label> <input type="text" class="form-control" formControlName="name" #name /> </div> <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger"> <div *ngIf="angForm.controls['name'].errors.required"> Name is required. </div> </div> <div class="form-group"> <label class="col-md-4">Coin Price</label> <input type="text" class="form-control" formControlName="price" #price/> </div> <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger"> <div *ngIf="angForm.controls['price'].errors.required"> Price is required. </div> </div> <div class="form-group"> <button (click)="addCoin(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button> </div> </form> </div> </div>
Also, we need to write the validation logic in the create.component.ts file.
// create.component.ts import { Component, OnInit } from '@angular/core'; import { CoinService } from '../../coin.service'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { title = 'Add Coin'; angForm: FormGroup; constructor(private coinservice: CoinService, private fb: FormBuilder) { this.createForm(); } createForm() { this.angForm = this.fb.group({ name: ['', Validators.required ], price: ['', Validators.required ] }); } addCoin(name, price) { this.coinservice.addCoin(name, price); } ngOnInit() { } }
Write the coin.service.ts file to insert the data into the database.
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Injectable() export class CoinService { constructor(private http: HttpClient) { } addCoin(name, price) { const uri = 'http://localhost:4000/coins/add'; const obj = { name: name, price: price }; this.http.post(uri, obj) .subscribe(res => console.log('Done')); } }
Start the node.js server by typing: node server. Then, if all the database configuration is right, you can see the data is inserted into the database.
Step 13: Display the data to the front end.
In the index.component.html file, write the following code.
<table class="table table-hover"> <thead> <tr> <td>Coin Name</td> <td>Coin Price</td> <td colspan="2">Actions</td> </tr> </thead> <tbody> <tr *ngFor="let coin of coins"> <td>{{ coin.name }}</td> <td>{{ coin.price }}</td> <td><a [routerLink]="['/edit', coin._id]" class="btn btn-primary">Edit</a></td> <td><a routerLink="" class="btn btn-danger">Delete</a></td> </tr> </tbody> </table>
Also, you need to update the index.component.ts file and call the service functions to make an http get request.
import { CoinService } from './../../coin.service'; import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Component({ selector: 'app-index', templateUrl: './index.component.html', styleUrls: ['./index.component.css'] }) export class IndexComponent implements OnInit { coins: any; constructor(private http: HttpClient, private service: CoinService) {} ngOnInit() { this.getCoins(); } getCoins() { this.service.getCoins().subscribe(res => { this.coins = res; }); } }
Write the coin.service.ts file to make an http get request.
import { Injectable } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class CoinService { result: any; constructor(private http: HttpClient) {} addCoin(name, price) { const uri = 'http://localhost:4000/coins/add'; const obj = { name: name, price: price }; this .http .post(uri, obj) .subscribe(res => console.log('Done')); } getCoins() { const uri = 'http://localhost:4000/coins'; return this .http .get(uri) .map(res => { return res; }); } editCoin(id) { const uri = 'http://localhost:4000/coins/edit/' + id; return this .http .get(uri) .map(res => { return res; }); } }
Now, move over to http://localhost:4200/index.
It will display the data. Now, we need to add the actions to Edit and Delete.
Step 14: Edit and Delete the Coins.
First, we must fetch the data from the database and display it in the edit form. So first, the edit form looks like this. Next, write the following code in the edit.component.html file.
<div class="panel panel-primary"> <div class="panel-heading"> {{ title }} </div> <div class="panel-body"> <form [formGroup]="angForm" novalidate> <div class="form-group"> <label class="col-md-4">Coin Name</label> <input type="text" class="form-control" formControlName="name" #name [(ngModel)] = "coin.name"/> </div> <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger"> <div *ngIf="angForm.controls['name'].errors.required"> Name is required. </div> </div> <div class="form-group"> <label class="col-md-4">Coin Price</label> <input type="text" class="form-control" formControlName="price" #price [(ngModel)] = "coin.price" /> </div> <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger"> <div *ngIf="angForm.controls['price'].errors.required"> Price is required. </div> </div> <div class="form-group"> <button (click)="updateCoin(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Update</button> </div> </form> </div> </div>
Okay, the next step is to code the edit.component.ts file.
// edit.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { CoinService } from './../../coin.service'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'] }) export class EditComponent implements OnInit { coin: any; angForm: FormGroup; title = 'Edit Coin'; constructor(private route: ActivatedRoute, private router: Router, private service: CoinService, private fb: FormBuilder) { this.createForm(); } createForm() { this.angForm = this.fb.group({ name: ['', Validators.required ], price: ['', Validators.required ] }); } updateCoin(name, price) { this.route.params.subscribe(params => { this.service.updateCoin(name, price, params['id']); this.router.navigate(['index']); }); } ngOnInit() { this.route.params.subscribe(params => { this.coin = this.service.editCoin(params['id']).subscribe(res => { this.coin = res; }); }); } }
Now, also write the code into the coin.service.ts file.
import { Injectable } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class CoinService { result: any; constructor(private http: HttpClient) {} addCoin(name, price) { const uri = 'http://localhost:4000/coins/add'; const obj = { name: name, price: price }; this .http .post(uri, obj) .subscribe(res => console.log('Done')); } getCoins() { const uri = 'http://localhost:4000/coins'; return this .http .get(uri) .map(res => { return res; }); } editCoin(id) { const uri = 'http://localhost:4000/coins/edit/' + id; return this .http .get(uri) .map(res => { return res; }); } updateCoin(name, price, id) { const uri = 'http://localhost:4000/coins/update/' + id; const obj = { name: name, price: price }; this .http .post(uri, obj) .subscribe(res => console.log('Done')); } }
I have already written an edit and update service to make an API call. So till now, Create, Read, Update is complete. Now, take a look at Delete.
Now, I am coding the whole index.component.html file.
<table class="table table-hover"> <thead> <tr> <td>Coin Name</td> <td>Coin Price</td> <td colspan="2">Actions</td> </tr> </thead> <tbody> <tr *ngFor="let coin of coins"> <td>{{ coin.name }}</td> <td>{{ coin.price }}</td> <td><a [routerLink]="['/edit', coin._id]" class="btn btn-primary">Edit</a></td> <td><button (click)="deleteCoin(coin._id)" class="btn btn-danger">Delete</button></td> </tr> </tbody> </table>
Write the deleteCoin() function edit.component.ts file.
deleteCoin(id) { this.service.deleteCoin(id).subscribe(res => { console.log('Deleted'); }); }
Finally, the whole coin.service.ts file looks like this.
import { Injectable } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class CoinService { result: any; constructor(private http: HttpClient) {} addCoin(name, price) { const uri = 'http://localhost:4000/coins/add'; const obj = { name: name, price: price }; this .http .post(uri, obj) .subscribe(res => console.log('Done')); } getCoins() { const uri = 'http://localhost:4000/coins'; return this .http .get(uri) .map(res => { return res; }); } editCoin(id) { const uri = 'http://localhost:4000/coins/edit/' + id; return this .http .get(uri) .map(res => { return res; }); } updateCoin(name, price, id) { const uri = 'http://localhost:4000/coins/update/' + id; const obj = { name: name, price: price }; this .http .post(uri, obj) .subscribe(res => console.log('Done')); } deleteCoin(id) { const uri = 'http://localhost:4000/coins/delete/' + id; return this .http .get(uri) .map(res => { return res; }); } }
In this tutorial, I have not done any code that does not prevent the page refresh; You need to refresh the page to see the changes. So I want you to know that this is how you can write the CRUD application.
That’s it.
Hi,
Thanks for the tutorial Krunal. You just made a lil mistake in this part:
”
Also, write the deleteCoin() function edit.component.ts file.
deleteCoin(id) {
this.service.deleteCoin(id).subscribe(res => {
console.log(‘Deleted’);
});
}
”
It should be in index.component.ts not in edit.component.ts.
And it works for me! 😉
thxx
Thanks Kao you solved my problem too.
Its also resolved my issue. Thank you Kao…
I am getting error
ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2018-02-14T07:18:40.424Z
Hash: 06a24f8b3c0e341c365a
Time: 3565ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 2.93 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 636 bytes [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 33.8 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 853 kB [initial] [rendered]
ERROR in TypeError: Cannot read property ‘loadChildren’ of null
at _collectLoadChildren (/home/rama/work/angular/ng5crud/node_modules/@angular/compiler/bundles/compiler.umd.js:29034:21)
at listLazyRoutes (/home/rama/work/angular/ng5crud/node_modules/@angular/compiler/bundles/compiler.umd.js:29009:49)
at visitLazyRoute (/home/rama/work/angular/ng5crud/node_modules/@angular/compiler/bundles/compiler.umd.js:31176:47)
at AotCompiler.listLazyRoutes (/home/rama/work/angular/ng5crud/node_modules/@angular/compiler/bundles/compiler.umd.js:31144:20)
at AngularCompilerProgram.listLazyRoutes (/home/rama/work/angular/ng5crud/node_modules/@angular/compiler-cli/src/transformers/program.js:156:30)
at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/home/rama/work/angular/ng5crud/node_modules/@angular/compiler-cli/src/ngtools_api.js:44:36)
at AngularCompilerPlugin._getLazyRoutesFromNgtools (/home/rama/work/angular/ng5crud/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:249:66)
at Promise.resolve.then.then (/home/rama/work/angular/ng5crud/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:572:50)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
webpack: Failed to compile.
Try this in app.module.ts file: import { appRoutes } from ‘./routerConfig’;
and also change this in routeConfig.ts file.
export const appRoutes: Routes = [
{ path: ‘create’,
component: CreateComponent
},
{
path: ‘edit/:id’,
component: EditComponent
},
{ path: ‘index’,
component: IndexComponent
}
];
I tried your program on GitHub and when I tried to add the new coin, I was moved to the index page but no data was added, the index page is empty, same for the database.
Can you help me with this? I used ‘ng serve’ command to run.
Thank you very much
have you configured the mongodb database correctly?
How do I configure the data base? I got mongodb running with a data base named angularcrud but I don’t know if that’s enough.
// DB.js
module.exports = {
DB: ‘mongodb://localhost:27017/angularcrud’
};
Refer step 10 for this.
I have the same issue with a lack of mongodb and angular knowledge. In the server.js you write: require(‘./config/DB’) , so we need a folder called “config” to put in the DB.js . I am also not sure if I put the server.js on the right place /src/server.js ?
I managed it:
In the server.js you write: require(‘./config/DB’) , so we need a folder called “config” to put in the DB.js .
Start MongoDB (cmd: go into your install directory)
mongod.exe –dbpath “D:\DB\mongo”
(the dbpath defines where the db should be placed, if you don’t like the default place)
Start the Server (cmd: change directory to the folder where the server.js is)
node server.js
Listening on port 4000
Database is connected
(you will also see in the cmd-shell from MongoDB something like “connection accepted from …)
start the application and enjoy it (add coins, switch the url to /index. – after edit you need to refresh your browser window (F5) )
webpack-internal:///…e/esm5/core.js:1654 ERROR
HttpErrorResponse
error
:
“unable to save to database”
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
“Http failure response for http://localhost:4000/coins/add: 400 Bad Request”
name
:
“HttpErrorResponse”
ok
:
false
status
:
400
statusText
:
“Bad Request”
url
:
“http://localhost:4000/coins/add”
__proto__
:
HttpResponseBase
I am getting the same error.
you can help me, please.
I am getting the same error.
can you please help me.
same error here, any luck w/ fixing?
Hi Krunal,
This post is really helpful for beginners like me. But I don’t know mongo DB. If u have Angular CRUD tutorial with spring boot , Jpa and PostgreSQL/MySQL, can u send me the code.
My email is sarjitakonjengbam@gmail.com
Sorry, do not know the JAVA or Spring. But you can use angular for frontend and if you know Java then you can integrate with this code easily.
Salut Sarjita,
tu as reçu une réponse ?
Krunal – this is great. Finally a tutorial to walk through a mean stack application that doesnt have about of bloated crap. Thanks
Thanks man
Blocage d’une requête multi-origines (Cross-Origin Request) : la politique « Same Origin » ne permet pas de consulter la ressource distante située sur http://localhost:3000/coins/add. Raison : jeton « content-type » manquant dans l’en-tête CORS « Access-Control-Allow-Headers » du canal de pré-vérification des requêtes CORS.
Please use CORS module inside node.js express application by typing npm install cors –save and then use it as middleware.
thanks but it show me these error when i add new coins :
OPTIONS http://localhost:3000/coins/add net::ERR_CONNECTION_REFUSED
how can i run ng serve and node server in the same time ?
You open two tabs in terminal and run both simultaneously
Thank you so much Dude….
Hi thanks for this tutorial.
but at home I have a problem.
“http: // localhost: 4000 / net corners :: ERR_CONNECTION_REFUSED”
you can help me please.
Hi thanks for this tutorial.
When we navigate to http://localhost:4200/index. It says site can’t reach.
if it is the http://localhost:4000/index or http://localhost:4000/coins/index
still it is throwing error : Cannot GET /coins/index
Please help I am struck here
what is the landing/home page url.
if there are any changes.
please us know.
Hi Krunal
what is the command to run app
> ng serve or node server
what is the landing/home page.
what is the url
Please let us know.
I am struck
For Node.js it is the node server and for Angular it is ng serve
You need to start both of the servers. Node.js will help you to serve the data to the Angular Application.
thak you!!!!
I have just started learning angular 5. Your article is great.
i am new to angular.
i am getting the following error when executed.
Failed to compile.
node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module ‘rxjs-compat/Observable’.
src/app/app.module.ts(9,32): error TS2307: Cannot find module ‘.components/index/index.component’.
src/app/app.module.ts(10,33): error TS2307: Cannot find module ‘.components/create/create.component’.
src/app/app.module.ts(11,31): error TS2307: Cannot find module ‘.components/edit/edit.component’.
src/app/coin.service.ts(5,10): error TS2305: Module ‘”C:/xampp/htdocs/ngcrud/ng5crud/node_modules/rxjs/Observable”‘ has no exported member ‘Observable’.
and so on ….
thanks very much for the article. for the the first time i was able to learn how to build with a database.
however when i run node server i get the followig
Listening on port 4000
Can not connect to the databaseMongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
You need to start mongodb database server.
I am facing reload issue on some time interval (every 2-5 seconds) on every page. Please suggest what I am doing wrong.I have followed your steps completely but not getting what is the issue.
Hi, Kunal
please help me for this issue.
Thanks,
Jignesh
Step 14: Don’t put deleteCoin(coin._id){…} into edit.component.ts because you call it from the index.component.html it ought to be in the index.component.ts
Hello sir,
i have some other error in console “Http failure response for (unknown url): 0 Unknown Error”.
error: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: “http://localhost:4000/coins”, readyState: 4, … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: “http://localhost:4000/coins”, readyState: 4, … }
target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: “http://localhost:4000/coins”, readyState: 4, … }
timeStamp: 544162
total: 0
type: “error”
When i insert data in DB
Hello,
Great tutorial, many thanks ! But i have a question. How to reload index page after add, edit or delete coin ?
Does I add “trackBy” in *ngFor ? And how to implement in the code ?
I am not getting the response after ‘Add’, saying that it is added successfully, but the ‘done’ in console is appearing. Also ‘Index’ is not displaying the data from DB. Can you please help me to resolve these issues.
I am also facing the same issue, any solution here?
Hi how do you get a single result from mongo using this crud model?
Thank you so much for this tutorial. For some reason, the app is inserting into the db twice. When you have a chance, please read what I posted on stackoverflow and let me know if there is something that I can do – https://stackoverflow.com/questions/51219696/anuglar-6-post-subscribe-inserting-record-twice
Hi Krunal, I am very thankfull to you for this tutorial. But I am Not knowing MongoDB. So, Please can you provide me a CRUD Tutorial With PHP And MySQL DATABASE.
My Email ID is : er.mr.ashish@gmail.com. Please reply me as soon as possible.
Thanks,
This site can’t be reached
localhost refused to connect.
Search Google for localhost 4200
ERR_CONNECTION_REFUSED
Thank you for such a great Article.
But I am stuck at below error
Development Environment : is VS Code.
DB : Mongo Db
This site can’t be reached
localhost refused to connect.
Search Google for localhost 4200
ERR_CONNECTION_REFUSED
hey, edit component displays error saying 404 not found, i have a page for not found component
Thanks for your effort,
Do you have the same tutorial for mysql, instead of mongodb?
or
what changes may i require to make in this project for that?
400 BAD REQUEST – as stated above as well. Any ideas???
when i am hitting localhost url it is showing index file content may be i have replaced old index file can somebody help me out
i am getting this error when adding the coin
POST http://localhost:4200/coins/add 404 (Not Found)
for all routes save error
My compliments for your tutorial it is simple and it worked at first launch
Can any one throw some light on the rxjs compatibility issue. Mr. Inap’s problem above is also my problem,
mkashab
Install rxjs-compat library by typing npm install rxjs-compat –save
Which is the ‘root’ you have mentioned here for creating ‘server.js’ and ‘db.js’?
Is it the ‘app’ folder or the ‘src’ folder?
Thanks in advance!
Bonjour, quelqu’un pourrais m’aider, je eu ce problème en affichant mes données, merci et voici l’erreur ci-dessous:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: “OK”, url: “http://localhost:4201/api/show”, ok: false, …}
error: {error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHtt…,
Hi
Kunal
I tried to run node and angular
but your project not working node side not run kindly fix it
What’s up, every time i used to check webpage posts here in the early hours in the dawn, because i enjoy to gain knowledge of
more and more.