0

I have a service class book.service.ts as:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Book } from '../common/book';
import { BookCategory } from '../common/book-category';
import { Finalcart } from '../common/finalcart';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};


@Injectable({
  providedIn: 'root'
})
export class BookService {

  private finalCart="http://localhost:8080/api/test/";

  constructor(private httpClient:HttpClient) { }

  addFinalCart(finalCart:Finalcart){

  return this.httpClient.post(`${this.baseUrl}`+'finalCart',finalCart, httpOptions);   
}

The service method addFinalCart(finalCart:Finalcart) is getting called from component.ts file :

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

  cartItems: CartItem[] = [];
  totalPrice: number = 0;
  totalQuantity: number = 0;
  checkoutFormGroup: FormGroup;
   finalCart:Finalcart;

  constructor(private formBuilder: FormBuilder,private _cartService: CartService,
    private _bookService:BookService) { }

 
  ngOnInit() {
//I have not included all codes,only the required ones.
   }
  onSubmit() {
    if (this.checkoutFormGroup.invalid) {
      return;
  }
  console.log(this.cartItems);
  console.log('Purchase the books');
      let finalCart=new Finalcart(this.checkoutFormGroup.value.billingAddress,
    this.checkoutFormGroup.value.shippingAddress, this.checkoutFormGroup.value.creditCard, this.cartItems);
    
    console.log('finalcart is',finalCart);
    this._bookService.addFinalCart(this.finalCart);
  }
}

So,I have the JWT authentication and I have been already logged in successfully and while calling api :

http://localhost:8080/api/test/finalCart

The api that I am exposing in spring boot is not called.However,when I called the api from postman then,the api is being called successfully in spring boot,but from postman I have passed the token information also,but while from service class of angular I haven't send the user information.

package in.ashwin.onlinebookstore.controller;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {
    
    @Autowired
    UserDetailsServiceImpl userdetailService;
    
    @Autowired
    private OrderRepository orderRep;
    
    @Autowired
    private BookRepository bookrepository;
    
    @Autowired
    private CartItemRepository cartItemRepo;
    
    @Autowired
    private OrderDetailsRepository orderDetailRepostiory;
    

    
    @Autowired
    private BillingaddressRepository billAddressRepo;
    
    @Autowired
    private ShippingaddressRepository shippingAddressRepo;
    
    @PostMapping("/finalCart")
    @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
    public String finalCart(@RequestBody Finalcart finalCart,HttpServletRequest request) {
        String user=request.getUserPrincipal().getName();
       System.out.println(user);
       
       System.out.println(finalCart);
    
       UserDetailsImpl userDetails=(UserDetailsImpl)userdetailService.loadUserByUsername(user);
        User u=new User(userDetails.getId(),userDetails.getUsername(),userDetails.getPassword(),userDetails.getEmail());
     Order ord= orderRep.save(new Order(u,new Date()));
     System.out.println(ord);
     
     
     
    Billingaddress ba= billAddressRepo.save(new Billingaddress(finalCart.getBillingAddress(),ord));
    System.out.println(ba);
     
     Shippingaddress sa=shippingAddressRepo.save(new Shippingaddress(finalCart.getShippingAddress(),ord));
     System.out.println(sa);
     
     finalCart.getCartItem().forEach(s->{
         Optional<Book> b=bookrepository.findById(Long.valueOf(s.getBookId()).longValue());
        CartItem c=cartItemRepo.save(new CartItem(s.getName(),s.getImageUrl(),s.getUnitPrice(),s.getQuantity(), b.get()));
        orderDetailRepostiory.save(new OrderDetails(c,ord));    
     });
     
     
       System.out.println(userDetails.getUsername()+userDetails.getPassword());
        System.out.println("entered here");
        System.out.println(finalCart);
        System.out.println(finalCart.getBillingAddress());
        System.out.println(finalCart.getShippingAddress());
        System.out.println(finalCart.getCreditCard());
        return "null";
    }
}

I see there is nothing printed in my console in eclipse.I think I made mistake while sending information from angular service class.

1 Answer 1

1

You need to subscribe to the addFinaCart inorder for API call to work

this._bookService.addFinalCart(this.finalCart).subscribe(
        (response) => {
        console.log(response.body);
        },
       (err)=>{
       console.log("Error",err); //======> In case of failure
       }
)
Sign up to request clarification or add additional context in comments.

2 Comments

Since I have two parameter in spring boot finalCart(@RequestBody Finalcart finalCart,HttpServletRequest request) , I got error since there is HttpServletRequest. How can I set it as required false from angular service method?
my api is being called when I put the subscribe methos

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.