Mountain View


Angular-Spring rest example

Posted On : 09-Jan-2019 [339]



==============module=============

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }



=================component============

import { Component } from '@angular/core';
import { book} from './book';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'sample';
  bookName='Bagavadgeetha';
  bookTitle='asItis';
  id ='10';
  ids : string[];
  staticBooks:book[] = [
    new book('1','java','java reference'),
    new book('2','spring', 'spring refernce'),
    new book('3' ,'angular','angular reference')
  ];
  newBook: book = new book(null , null , null);
  dynamicBooks: book[];
  onAdd(){
    this.staticBooks.push(new book(this.newBook.id , this.newBook.bookName ,this.newBook.bookTitle));
    this.newBook.id =null;
    this.newBook.bookName =null;
    this.newBook.bookTitle =null;
  }
  onDelete(n){
    this.staticBooks.splice(n,1);
  }
}



=================html===============



<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
   <input type="text" [(ngModel)] ="bookName" />
   <input type="text" [(ngModel)] ="bookTitle" />
   <input type="text" [(ngModel)] ="id" />
  </li><br />
  <li>
    <table border="1">
      <tr><th>Book id</th> <th>Book name</th><th>Book title</th></tr>
      <tr *ngFor = "let book of staticBooks ;let i=index"><td>{{book.id}}</td> <td>{{book.bookName}}</td><td>{{book.bookTitle}}</td>
      <td><input type="button" value ="delete book" (click) ="onDelete(i)" /></td>
      </tr>

      <tr><td><input type="text" [(ngModel)] ="newBook.id" required/></td> 
        <td><input type="text" [(ngModel)] ="newBook.bookName" required/></td>
        <td><input type="text" [(ngModel)] ="newBook.bookTitle" required/></td>
        <td><input type="button" value ="add book" (click) ="onAdd()" /></td>
        
      
      </tr>

    </table>
  </li>
</ul>

<router-outlet></router-outlet>




    #####################################
	
	
	
	StaticInjectorError(AppModule)

add your service one of the below

@NgModule({
  ...
  providers: [ yourServiceName ]
})

@Component({
  ...
  providers: [ yourServiceName ]
})



=============book component html ============


<h4>Working with resrvices</h4>
<table border="1">

        <tr><td><input type="text"  /></td> </tr>
            <tr></tr> 

  <tr><th>Book id</th> <th>Book name</th><th>Book title</th></tr>
  <tr *ngFor = "let book of staticBooks ;let i=index"><td>{{book.id}}</td> <td>{{book.bookName}}</td><td>{{book.bookTitle}}</td>
  <td><input type="button" value ="delete book" (click) ="deleteBookById(book)" /></td>
  </tr>
  <tr><td><input type="text" [(ngModel)] ="newBook.id" required/></td> 
    <td><input type="text" [(ngModel)] ="newBook.bookName" required/></td>
    <td><input type="text" [(ngModel)] ="newBook.bookTitle" required/></td>
    <td><input type="button" value ="add book" (click) ="addbook()" /></td>
  </tr>
</table>

=======================

import { Component , OnInit } from '@angular/core';
import { book} from './book';
import {BookService} from './book.service'


@Component({
    selector: 'app-book',
    templateUrl: './book.component.html',
    styleUrls: ['./app.component.css']
  })

  export class BookComponent implements OnInit {

   

      public addbook(book) {
      }
    
      public deleteBookById(book) {
      }
    
      public getBookById(book) {
      }

      public getAllBookIds() {
      }

      ngOnInit() {
        
      }
  }    
  
  
  ==================
  
  import {Injectable} from '@angular/core';
import {HttpHeaders ,HttpClient , HttpClientModule} from '@angular/common/http';
import {book} from './book';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };
@Injectable()
export class BookService{

    private url = "http://localhost:9099/tinyurl/";
    newBook: book = new book(null , null , null);
    
    constructor(private http:HttpClient) {

    }
     public addbook(book) {
        return this.http.post<String>(this.url+"addBook", book);        
      }
    
      public deleteBookById(book) {
        return this.http.delete<string>(this.url + "deleteBookById/"+ book.id);
      }
    
      public getBookById(book) {
        return this.http.get<book>(this.url+"getBookByid/"+book.id);        
      }

      public getAllBookIds() {
        return this.http.get<string[]>(this.url+"getBooks");        
      }

}
=========================

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {BookComponent} from './book.component';
import {HttpClientModule} from '@angular/common/http';
import {BookService} from './book.service'



@NgModule({
  declarations: [
    AppComponent ,
    BookComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [BookService],
  bootstrap: [AppComponent]
})
export class AppModule { }

===========================

import { Component } from '@angular/core';
import { book} from './book';
import {BookService} from './book.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'sample';
  bookName='gfgsdfs';
  bookTitle='asItis';
  id ='10';
  ids : string[];
  staticBooks:book[] = [
    new book('1','java','java reference'),
    new book('2','spring', 'spring refernce'),
    new book('3' ,'angular','angular reference')
  ];
  newBook: book = new book(null , null , null);
  dynamicBooks: book[];

  constructor( private bookService: BookService) {
  }
  onAdd(){
    this.staticBooks.push(new book(this.newBook.id , this.newBook.bookName ,this.newBook.bookTitle));
    this.newBook.id =null;
    this.newBook.bookName =null;
    this.newBook.bookTitle =null;
  }
  onDelete(n){
    this.staticBooks.splice(n,1);
  }
}

==================================

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
   <input type="text" [(ngModel)] ="bookName" />
   <input type="text" [(ngModel)] ="bookTitle" />
   <input type="text" [(ngModel)] ="id" />
  </li><br />
  <li>
    <table border="1">
      <tr><th>Book id</th> <th>Book name</th><th>Book title</th></tr>
      <tr *ngFor = "let book of staticBooks ;let i=index"><td>{{book.id}}</td> <td>{{book.bookName}}</td><td>{{book.bookTitle}}</td>
      <td><input type="button" value ="delete book" (click) ="onDelete(i)" /></td>
      </tr>
      <tr><td><input type="text" [(ngModel)] ="newBook.id" required/></td> 
        <td><input type="text" [(ngModel)] ="newBook.bookName" required/></td>
        <td><input type="text" [(ngModel)] ="newBook.bookTitle" required/></td>
        <td><input type="button" value ="add book" (click) ="onAdd()" /></td>
      </tr>
    </table>

   <app-book></app-book>
  </li>
</ul>

<router-outlet></router-outlet>

============================


package com.rs.tiny.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.rs.tiny.dao.BookDto;
import com.rs.tiny.dto.Reponse;
import com.rs.tiny.dto.TinyUrlDto;
import com.rs.tiny.services.TinyUrlService;

@RestController
public class ServicesController {

private static final Logger logger = LoggerFactory.getLogger(ServicesController.class);
@Autowired
private TinyUrlService tinyUrlService;

@PostMapping(value = "/addBook", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> addBook(@RequestBody BookDto bookDto) {
ResponseEntity<Object> responseEntity = null;
try {
tinyUrlService.addBook(bookDto);
Reponse response = new Reponse();
response.setMesage("Added successfully...");
responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return responseEntity;
}

@PostMapping(value = "/getBooks", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getBooks() {
ResponseEntity<Object> responseEntity = null;
try {
Object response = tinyUrlService.getBooks();
responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return responseEntity;
}
@GetMapping(value = "/getBookByid/{id}",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getBookByid(@PathVariable String id) {
ResponseEntity<Object> responseEntity = null;
try {
Object response = tinyUrlService.getBookByid(id);
responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return responseEntity;
}
@DeleteMapping(value = "/deleteBookById/{id}")
public ResponseEntity<Object> deleteBookById(@PathVariable String id) {
ResponseEntity<Object> responseEntity = null;
try {
tinyUrlService.deleteBookById(id);
Reponse response = new Reponse();
responseEntity = new ResponseEntity<>("Deleted successfully...", HttpStatus.OK);
} catch (Exception e) {
responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return responseEntity;
}
}

===============================


package com.rs.tiny.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.transaction.Transactional;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.rs.tiny.controller.ServicesController;
import com.rs.tiny.dao.BookDto;
import com.rs.tiny.dao.TinyUrlDao;
import com.rs.tiny.dto.Reponse;
import com.rs.tiny.dto.TinyUrlDto;
import com.rs.tiny.entity.TinyUrlEntity;
import com.rs.tiny.entity.TinyUrlOtpEntity;
import com.rs.tiny.model.TinyUrlOtp;

@Repository
public class TinyUrlDaoImpl implements TinyUrlDao {
private static final Logger logger = LoggerFactory.getLogger(ServicesController.class);

@Autowired 
ServletContext context;

@Override
public void addBook(BookDto bookDto) {
Map<String ,BookDto> bookMap = getBookMapFromContext();
bookMap.put(bookDto.getId(), bookDto);
logger.info("add book ::: " ,bookMap );

context.setAttribute("bookMap", bookMap);
}

@Override
public Set<String> getBooks() {
Map<String ,BookDto> bookMap = getBookMapFromContext();
Set<String> booksIdList = bookMap.keySet();
return booksIdList;
}

@Override
public BookDto getBookByid(String id) {
Map<String ,BookDto> bookMap = getBookMapFromContext();
return bookMap.get(id);
}

@Override
public void deleteBookById(String id) {
Map<String ,BookDto> bookMap = getBookMapFromContext();
bookMap.remove(id);
logger.info("delete book ::: " , bookMap );

context.setAttribute("bookMap", bookMap);
}
public Map<String ,BookDto> getBookMapFromContext (){
Map<String ,BookDto> bookMap = new HashMap<String ,BookDto>();
Object obj = context.getAttribute("bookMap");
if(obj!=null) {
bookMap =(Map<String ,BookDto> )obj;
}
return bookMap;
}
}

***********************New Angular ************************

import { Component , OnInit } from '@angular/core';
import { book} from './book';
import {BookService} from './book.service';
import {HttpClientModule} from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [BookService]

})
export class AppComponent implements OnInit {
  title = 'sample';
  bookName='Bagavadgeetha';
  bookTitle='asItis';
  id ='10';
  ids : string[];
  addstatus :string;
  searchString :string;
  getBookErr :string;
 /* staticBooks:book[] = [
    new book('1','java','java reference'),
    new book('2','spring', 'spring refernce'),
    new book('3' ,'angular','angular reference')
  ];*/
 // staticBooks:book[]=[new book(null , null , null)];
 staticBooks:book[]=[];
  newBook: book = new book(null , null , null);
  newBookTemp: book = new book(null , null , null);

  dynamicBooks: book[];
  constructor( private bookService: BookService) {
  }
  onAdd(){
    this.staticBooks.push(new book(this.newBook.id , this.newBook.bookName ,this.newBook.bookTitle));
    this.newBook.id =null;
    this.newBook.bookName =null;
    this.newBook.bookTitle =null;
  }
  onDelete(n){
    this.staticBooks.splice(n,1);
  }


  public addbook(book) {
    alert("adding");
    this.bookService.addbook(book)
      .subscribe( data => {
        alert(data);
      })
      
  }

  public deleteBookById(book , n) {
    //this.bookService.deleteBookById(book).subscribe( data => {
      //alert(this.ids);
      this.staticBooks.splice(n,1);


    //});
  }

  public getBookById() {
    
    this.bookService.getBookById(this.searchString).subscribe( data => {
      this.newBookTemp = data;
      //alert(this.ids);
      alert(this.newBookTemp);
      if(this.newBookTemp!=null){
      this.staticBooks.push(this.newBookTemp);
      this.getBookErr ="";
      } else{
         this.getBookErr ="Book with id :" + this.searchString+"not avalable";
      }

    });

    this.staticBooks.push
  }

  public getAllBookIds() {
  }

  ngOnInit() {
    this.bookService.getAllBookIds().subscribe( data => {
        this.ids = data;
        alert(this.ids);
      });
  }
}
==================================

import {Injectable} from '@angular/core';
import {HttpHeaders ,HttpClient , HttpClientModule} from '@angular/common/http';
import {book} from './book';


const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };
@Injectable()
export class BookService{

    private url = "http://localhost:8080/";
    newBook: book = new book(null , null , null);
    
    constructor(private http:HttpClient) {

    }
     public addbook(book) {
        return this.http.post<String>(this.url+"addBook", book);        
      }
    
      public deleteBookById(book) {
        return this.http.delete<string>(this.url + "deleteBookById/"+ book.id);
      }
    
      public getBookById(id) {
          alert(id);
        return this.http.get<book>(this.url+"getBookByid/"+id);        
      }

      public getAllBookIds() {
        return this.http.get<string[]>(this.url+"getBooks");        
      }

}

=====================

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<ul>
 


  <li>
    

<h4>Dynamic data</h4>


<table border="1">
  <tr><th>Book id</th> <th>Book name</th><th>Book title</th></tr>
  

  <tr><td><input type="text" [(ngModel)] ="newBook.id" required/></td> 
    <td><input type="text" [(ngModel)] ="newBook.bookName" required/></td>
    <td><input type="text" [(ngModel)] ="newBook.bookTitle" required/></td>
    <td><input type="button" value ="add book" (click) ="addbook(newBook)" /></td>
    
  
  </tr>
<tr></tr>
</table>

<h4>Searching</h4>

<table border="1">
  

  <tr><td><input type="text" [(ngModel)] ="searchString" required/></td> 
    <td><input type="button" value ="addToGrid" (click) ="getBookById()" /></td>
  </tr>
  <tr>{{getBookErr}}</tr>
<tr></tr>
</table>
<br />
<br />

<table border="1">
  <tr><th>Book id</th> <th>Book name</th><th>Book title</th></tr>
  <tr *ngFor = "let book of staticBooks ;let i=index">
    <td *ngIf="book.id!=null">{{book.id}}</td> <td>{{book.bookName}}</td><td>{{book.bookTitle}}</td>
  <td *ngIf="book.id!=null"><input type="button" value ="delete book" (click) ="onDelete(i)" /></td>
  </tr>
<!--
  <tr><td><input type="text" [(ngModel)] ="newBook.id" required/></td> 
    <td><input type="text" [(ngModel)] ="newBook.bookName" required/></td>
    <td><input type="text" [(ngModel)] ="newBook.bookTitle" required/></td>
    <td><input type="button" value ="add book" (click) ="onAdd()" /></td>
    
  
  </tr>-->

</table>


  </li>
</ul>

<router-outlet></router-outlet>


=====================================

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {BookService} from './book.service'
import {HttpClientModule} from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [BookService],
  bootstrap: [AppComponent]
})
export class AppModule { }

=====================================

The easy way is to just add the extension in google chrome to allow access using CORS.

(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)

Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.

Or

In Windows, paste this command in run window

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.

===================================================

Cannot read property 'push' of undefined


private userList: User[] = []







Related Articles
Recent Articles
Most Viewed Articles