Reputation: 932
I'm having trouble making a POST request from an Angular frontend service class to my spring backend controller.
I am trying to get a log.info message to display from the controller, but it isn't working unless I manually use Swagger to make the call.
I don't think the issue is with the Java Rest Controller as Swagger can make the call to it.
I don't think there is an issue with my service class post request not being called, as I'm able to get the console.log message to display.
I don't think there is an issue with my resourceUrl in my service class as that is working fine with other REST calls.
I think it's something with how I am formatting my postRequest.
(Typescript service class)
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SERVER_API_URL } from 'app/app.constants';
import { DataModel} from 'app/shared/model/data-model.model';
@Injectable({ providedIn: 'root' })
export class DataModelService {
public resourceUrl = SERVER_API_URL + 'services/api/data-model';
constructor(protected http: HttpClient) {}
postRequest(dataModel: DataModel, status: string): Observable<DataModel> {
console.log('post rest service called with status ' + status);
return this.http.post<DataModel>(`${this.resourceUrl}/${status}`, dataModel);
}
(Typescript component class)
export class Component implements OnInit, OnDestroy {
...
constructor( protected dataModelService DataModelService) { }
userClicks(dataModel: DataModel): void {
/* eslint-disable no-console */
console.log('button clicked');
console.log(dataModel);
/* eslint-enable no-console */
this.dataModelService.postRequest(dataModel, 'Status changed');
}
(Java Spring REST Controller)
@RestController
@RequestMapping("/api")
public class RestResource {
@PostMapping("/data-model/{status}")
public ResponseEntity<DataModelDTO> create(@Valid @RequestBody DataModelDTO dataModelDTO, @PathVariable String status) throws URISyntaxException{
log.info(dataModelDTO.toString() + " status " + status);
return ResponseEntity.ok().body(dataModelDTO);
}
}
Upvotes: 0
Views: 864
Reputation: 15105
You need to subscribe
to the Observable
, otherwise the request won't be triggered. Observables are "lazy".
this.dataModelService.postRequest(dataModel, 'Status changed')
.subscribe(response => {
// Do something with the response optionally
}, error => {
// Do something if an error occurs
});
Upvotes: 3