0

main book component code (book.component.ts)

import { Component, OnInit } from '@angular/core';
import { BookService } from './../app/book.service';
import { Observable } from 'rxjs/observable';
import 'rxjs/Rx';
import { Book } from './../app/Book';

@Component({
    selector: 'book',
    moduleId: module.id,
    templateUrl: 'book.component.html',
    providers: [BookService],
})

export class BookComponent {
    books: Book[];

    constructor(private bookService: BookService) {
        this.bookService.getBooks()
            .subscribe(books => {
                this.books = books;
            });
    }
    removeBook(id: number) {
        var books = this.books;
        this.bookService.removeBook(id).subscribe(data => {
            if (data.n == 1) {
                for (var i = 0; i < books.length; i++) {
                    if (books[i].id == id) {
                        books.splice(i, 1);
                    }
                }
            }
        });
    }
}

service page (book.service.ts)

import { Injectable } from '@angular/core';
import { Http,Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BookService{
    constructor(private http: Http){
        console.log('BookService Started....')
    }

    headers:string;

    getBooks(){
        return this.http.get('/api/books').map(res => res.json());
    }

    removeBook(id: number){
        return this.http.delete('/api/book/'+ id).map(res => res.json());
    }
}

book component html code (book.component.html)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="main.css">
    <base href="/">
    <title> Books </title>
</head>
<body>
    <nav class="navbar navbar-inverse bg-inverse navbar-fixed-top">
        <div class="container">
            <p id="book">BOOKS</p>
        </div>
    </nav><br><br><br>
    <div class="container">
        <div class="row">
            <div class="col-md-4">
                <div class="card card-1">
                    <h1> ADD </h1>
                </div>
                <div class="card card-2">
                    <h2><i class="material-icons">add_circle</i> ADD </h2>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card card-1">
                    <h1> SEARCH </h1>
                </div>
                <div class="card card-2">
                    <div class="block2">
                        <input class="inner" type="text" placeholder="Enter id"> <button class="btn btn-sm inner" type="button"><span>Search</span></button>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card card-1">
                    <h1> LIST </h1>
                </div><br>
                <div *ngFor="let book of books">
                    <div class="card card-2" (click)="removeBook(book.id)">
                        <font color="#212121" size="3px"> <b> ID </b> </font> : {{book.id}} <br>
                        <font color="#212121" size="3px"> <b> NAME </b> </font>: {{book.name}}<br>
                        <font color="#212121" size="3px"> <b> AUTHOR </b></font>: {{book.author}}
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</html>

when i click delete which works fine by reloading the page manually but i need it refresh automaticllay

im using monogoose as database and rest api

NB: no errors

n00dl3
  • 21,213
  • 7
  • 66
  • 76

2 Answers2

1

First, don't splice in a left to right loop, it can cause issues.

removeBook(id: number) {
        var books = this.books;
        this.bookService.removeBook(id).subscribe(data => {
        if (data.n == 1) {
          let index = books.findIndex(book=>book.id===id)
          books.splice(i, 1);
        }
        });
    }

as you are modifying and not reassinging the array, ngFor does not get notified because you didn't specify a trackBy :

<div *ngFor="let book of books; trackBy:trackById">

and in your ts file :

trackById(book:Book,index:number){
    return book.id;
}

Otherwise you can just reassign instead of modifying the array in your component :

this.bookService.removeBook(id).subscribe(data => {
            if (data.n == 1)
                this.books = this.books.filter(book=>book.id!==id);
        });
Community
  • 1
  • 1
n00dl3
  • 21,213
  • 7
  • 66
  • 76
0

You can change your code in book.component.ts as follows :

export class BookComponent {
    books: Book[];

    constructor(private bookService: BookService) {}

    ngOnInit(){
        this.GetBooks();
    }

    GetBooks(){
        this.bookService.getBooks()
            .subscribe(books => {
                this.books = books;
        });
    }

    removeBook(id: number) {
        var books = this.books;
        this.bookService.removeBook(id).subscribe(data => {
            this.GetBooks();
        });
    }
}

Here, Method GetBooks() is called when you get response from api and your page will be reload automatically.

Darshita
  • 746
  • 6
  • 15
  • Unfortunately, this is not a good solution, since two server calls will most likely be made, unless there is a caching mechanism in bookService. – Mantas Mar 23 '17 at 09:16
  • the cache would not help, as he just made a DELETE request to the server... – n00dl3 Mar 23 '17 at 09:17
  • if you don't want to do two server calls then reload the page on the response. – Darshita Mar 23 '17 at 09:25
  • "if you don't want to do two server calls then reload the page on the response." Tell me by what kind of magic, it can skip a server call while reloading the page, I'm curious... – n00dl3 Mar 23 '17 at 09:28
  • method of `GetBooks()` is called on page load so server call will be definitely done.Sorry for that comment. @n00dl3 – Darshita Mar 23 '17 at 09:42
  • sry to ask this on this question...how to send value from html component to book component ? (have a input box and a button , need to pass value from input box to component by button click (function call)) tried ngModel and everything : @n00dl3 – Rahul Raveendran Mar 30 '17 at 05:06