-1

I want to call an api in the spring boot from my angular file For example:profile.service.ts

  private baseUrl = '/users';
  constructor(private http: HttpClient) {
  }
  getProfile(id: number): Observable<Object> {
    return this.http.get(`${this.baseUrl}` + '/load/' + `${id}`);
  }

and java file is : UsersController.java

@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private IUsersService iUsersService;

    @GetMapping("/list/grid")
    public Iterable<UsersViewModel> getAllEmployees() {
        return Dozer.mapList(iUsersService.getAll(), UsersViewModel.class);
    }

    @GetMapping("/load/{id}")
    public UsersViewModel getUserById(@PathVariable(value = "id") Long userId){
        return Dozer.mapClass(iUsersService.findById(userId).get(),UsersViewModel.class);
    }

The server is used for Angular is Apache and spring-boot port is 8090. Please Help me.

seyed ali ziaei
  • 198
  • 3
  • 15

1 Answers1

2

You are almost there.

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class UsersController {
...
}

the only implementation detail worth noting here is the use of the @CrossOrigin annotation. As the name implies, the annotation enables Cross-Origin Resource Sharing (CORS) on the server.

This step isn’t always necessary. Since we are deploying our Angular frontend to http://localhost:4200 and our Boot backend to http://localhost:8090, the browser would otherwise deny requests from one to the other.

Good to refer: https://www.baeldung.com/spring-boot-angular-web

Mebin Joe
  • 2,172
  • 4
  • 16
  • 22
  • @seyedaliziaei Cool. What is the issue you are facing ? Check the logs. Might be CORS issue. `@CrossOrigin` will help resolve if it is CORS,. – Mebin Joe Jul 29 '19 at 09:52
  • @seyedaliziaei what do you mean by global ? are you looking for this https://stackoverflow.com/questions/37980914/spring-global-cors-configuration-not-working-but-controller-level-config-does – Mebin Joe Jul 29 '19 at 10:10
  • please help me. crossorigin work for port 4200 but not working for port 80 when build angular to use in server – seyed ali ziaei Jul 29 '19 at 10:17
  • @seyedaliziaei If you are using default Apache 80 port the URL will be `http://localhost` without a specific port (as http default port is 80). Configure the Apache on some other port. In order for Access-Control-Allow-Origin permissions you need a valid port and URL like `http://domain:port/` to do that. Please refer https://www.digitalocean.com/community/questions/blocked-by-cors-policy-the-access-control-allow-origin-mean-stack for more information – Mebin Joe Jul 29 '19 at 10:35