Angular 4 CRUD Operation MVC – Angular 4 insert update delete

Angular 4 CRUD Operation MVC – Angular 4 insert update delete

In this Post We Will Explain About is Angular 4 CRUD Operation MVC – Angular 4 insert update delete With Example and Demo.

Welcome on infinityknow.com – Examples ,The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Angular 4 Tutorial – Create a CRUD App with Angular CLI

In this post we will show you Best way to implement Angular 4 CRUD, modals, animations, pagination, datetimepicker, hear for How to Angular 4 CRUD Operation MVC demo Example with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Example

product.service.ts:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Product } from './product'
@Injectable()
export class ProductSerice {
  constructor(private http: Http) {
  }
  private headers = new Headers({ 'Content-Type': 'application/json' });
  private productsUrl = 'api/products';
  getProducts(): Promise<Product[]> {
    return this.http.get(this.productsUrl)
      .toPromise()
      .then(response => response.json().data as Product[])
      .catch(this.handleError);
  }

  getProduct(id: number): Promise<product> {
    const url = `${this.productsUrl}/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Product)
      .catch(this.handleError);
  }


  createProduct(product: Product): Promise<product> {
    return this.http
      .post(this.productsUrl, JSON.stringify(product), { headers: this.headers })
      .toPromise()
      .then(res => res.json().data as Product)
      .catch(this.handleError);
  }

  updateProduct(product: Product): Promise<product> {
    const url = `${this.productsUrl}/${product.id}`;
    return this.http
      .put(url, JSON.stringify(product), { headers: this.headers })
      .toPromise()
      .then(() => product)
      .catch(this.handleError);
  }

  removeProduct(product: Product): Promise<void> {
    const url = `${this.productsUrl}/${product.id}`;
    return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}

createProduct(product: Product): get a product object as varibles and makes a methods http POST request to ‘api/products’ with data as new product object. Created simple product is returned as Promise.

READ :  Angularjs Reload data - update value without page refresh using Angularjs

updateProduct(product: Product): get a product object as varibles and makes methods http PUT request to simple update product details by id.

removeProduct(product: Product): get product object as varibles and makes methods http DELETE request to simple delete product by id.

product-info.component.html:

<div *ngif="product">
  <md-card style="width: 30%">
    <md-card-header>
      <md-card-title>{{product.model}} details!</md-card-title>
    </md-card-header>
    <md-card-content>
      <div><label>id: </label>{{product.id}}</div>
      <div>
        <label>model: </label>
        <input [(ngmodel)]="product.model" placeholder="model" />
      </div>
      <div>
        <label>Manufacturer: </label>
        <input [(ngmodel)]="product.manufacturer" placeholder="manufacturer" />
      </div>
    </md-card-content>
    <md-card-actions>
      <button md-button (click)="goBack()"> Back </button>
      <button md-button (click)="updateProduct()"> Update </button>
    </md-card-actions>
  </md-card>
  <div>

product-info.component.ts:

import 'rxjs/add/operator/switchMap'
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { Product } from '../product';
import { ProductSerice } from '../product.service'


@Component({
  selector: 'app-product-info',
  templateUrl: './product-info.component.html',
  styleUrls: ['./product-info.component.css']
})
export class ProductInfoComponent implements OnInit {

  product: Product;

  constructor(
    private productService: ProductSerice,
    private route: ActivatedRoute,
    private location: Location
  ) { }

  ngOnInit(): void {
    this.route.params.switchMap((params: Params) => this.productService.getProduct(+params['id']))
      .subscribe(product => this.product = product);
  }
  updateProduct(): void {
    this.productService.updateProduct(this.product);
    this.goBack();
  }
  goBack(): void {
    this.location.back();
  }

}

products.component.ts:

<h2>products</h2>
 
<form>
  <md-input-container style="width:30%">
    <input mdinput [(ngmodel)]="newProduct.model" placeholder="Model" name="model">
  </md-input-container>
  <md-input-container style="width:30%">
    <input mdinput [(ngmodel)]="newProduct.manufacturer" placeholder="Manufacturer" name="manufacturer">
  </md-input-container>
  <button md-raised-button (click)="createProduct(newProduct)">Create Product</button>
 
  <md-list>
    <md-list-item *ngfor="let product of products" (click)="showInfo(product)">
      <span>
          {{product.model}}
      </span>
      <span>
        <button md-raised-button (click)="removeProduct(product); $event.stopPropagation()">Delete</button>
      </span>
    </md-list-item>
  </md-list>
</form>

products.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Product } from '../product';
import { ProductSerice } from '../product.service';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsCompoenent implements OnInit {

  products: Product[];
  selectedProduct: Product;
  newProduct: Product;

  constructor(private router: Router, private productService: ProductSerice) {

  }

  ngOnInit() {
    this.productService.getProducts().then(products => this.products = products);
    this.newProduct = new Product();
  }

  createProduct(product: Product): void {

    this.productService.createProduct(product)
      .then(product => {
        this.products.push(product);
        this.selectedProduct = null;
      });
  }

  removeProduct(product: Product): void {
    this.productService
      .removeProduct(product)
      .then(() => {
        this.products = this.products.filter(b => b !== product);
        if (this.selectedProduct === product) { this.selectedProduct = null; }
      });
  }

  showInfo(product: Product): void {
    this.selectedProduct = product;
    this.router.navigate(['/information', this.selectedProduct.id]);
  }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
<!-- Include all the routing simple Data -->
import { AppComponent } from './app.component';
import { ProductInfoComponent } from './product-info/product-info.component';
import { ProductsCompoenent } from './products/products.component';
import { ProductSerice } from './product.service';
<!-- Include all the routing simple Data -->
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { BikesDatabaseService } from './products-database.service';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
<!-- Include all the routing simple Data -->
import { AppRoutingModule } from './app-routing/app-routing.module';
import { MaterialModule, MdList, MdListItem } from '@angular/material'

<!-- Include simple Data -->
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(BikesDatabaseService),
    MaterialModule.forRoot(),
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  declarations: [
    AppComponent,   //content AppComponent
    ProductsCompoenent,
    ProductInfoComponent,
  ],
  bootstrap: [AppComponent],
  providers: [ProductSerice],
})
export class AppModule { }

Example

READ :  Angular 6 CRUD Operations Application Tutorials

I hope you have Got Angular 4 CRUD, modals, animations, pagination, datetimepicker And how it works.I would Like to have FeadBack From My Blog(infinityknow.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(infinityknow.com) Are Most Always Welcome.

Add a Comment

Your email address will not be published. Required fields are marked *