Home > Enterprise >  connect the front and the back via a REST API in Maven project
connect the front and the back via a REST API in Maven project

Time:12-07

I would like to connect the front and the back of my Web App via a REST API, but I don't know how it works, technically speaking. I know that I have to make them communicate through the links first, but I don't know exactly where to place these links. I also don't know how I know that the communication is established, nor how to display data from the back in the front.

I know that the front communicates with the Resource of the back, but I do not see when the link is made with the front.

CodePudding user response:

This example is good start sample for REST-APIs (CRUD-Create/Read/Update/Delete) with spring boot and angular

enter image description here

#4 run backend (Spring boot) project in spring-boot-server sub directory

Run Spring Boot application

mvn spring-boot:run

The Spring Boot Server will export API at port 8081. enter image description here #5 run frontend (Angular) project

npm install
ng serve --port 8081

enter image description here

#6 launch browser end open frontend URL

http://localhost:8081

You can add tutorial , list, delete and update

enter image description here

enter image description here

You can call the list API by browser without angular enter image description here

#7 review & study code This overview enter image description here

list API server in Spring Boot at TutorialController.java file

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class TutorialController {

    @Autowired
    TutorialRepository tutorialRepository;

    @GetMapping("/tutorials")
    public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
        try {
            List<Tutorial> tutorials = new ArrayList<Tutorial>();

            if (title == null)
                tutorialRepository.findAll().forEach(tutorials::add);
            else
                tutorialRepository.findByTitleContaining(title).forEach(tutorials::add);

            if (tutorials.isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }

            return new ResponseEntity<>(tutorials, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

Get list API in Angular part at tutorial.service.ts file

const baseUrl = 'http://localhost:8080/api/tutorials';

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

  constructor(private http: HttpClient) { }

  getAll(): Observable<Tutorial[]> {
    return this.http.get<Tutorial[]>(baseUrl);
  }

  get(id: any): Observable<Tutorial> {
    return this.http.get<Tutorial>(`${baseUrl}/${id}`);
  }

  create(data: any): Observable<any> {
    return this.http.post(baseUrl, data);
  }

  update(id: any, data: any): Observable<any> {
    return this.http.put(`${baseUrl}/${id}`, data);
  }

  delete(id: any): Observable<any> {
    return this.http.delete(`${baseUrl}/${id}`);
  }

  deleteAll(): Observable<any> {
    return this.http.delete(baseUrl);
  }

  findByTitle(title: any): Observable<Tutorial[]> {
    return this.http.get<Tutorial[]>(`${baseUrl}?title=${title}`);
  }
}

Display in Angular for list at tutorials-list.component.html by tutorials-list.component.html

  <div >
    <h4>Tutorials List</h4>
    <ul >
      <li
        
        *ngFor="let tutorial of tutorials; let i = index"
        [class.active]="i == currentIndex"
        (click)="setActiveTutorial(tutorial, i)"
      >
        {{ tutorial.title }}
      </li>
    </ul>

    <button  (click)="removeAllTutorials()">
      Remove All
    </button>
  </div>

It's html's tutorials array variable binding with TutorialsListComponent's tutorials?: Tutorial[]; It was assigned values by tutorialService: TutorialService It injected at consructor()

export class TutorialsListComponent implements OnInit {

  tutorials?: Tutorial[];
  currentTutorial: Tutorial = {};
  currentIndex = -1;
  title = '';

  constructor(private tutorialService: TutorialService) { }

  ngOnInit(): void {
    this.retrieveTutorials();
  }

  retrieveTutorials(): void {
    this.tutorialService.getAll()
      .subscribe({
        next: (data) => {
          this.tutorials = data;
          console.log(data);
        },
        error: (e) => console.error(e)
      });
  }

Enjoy happy coding!

  • Related