Reputation: 978
I'm struggling to create a POST request in Angular v7 from a Service. My service class already has some get requests in it that pull data from my api. Now I need to post data and I can't figure out the format/syntax (still new to angular).
In VSCode I can see it says Property 'subscribe' does not exist on type
'void'.
Here is the service
Shipment.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import { Ziptastic } from '../interfaces/ziptastic';
import { ReturnShipment } from '../interfaces/return-shipment';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable({
providedIn: 'root'
})
export class ShipmentService {
private shipmentCreation = 'api/ReturnShipmentQueues';
constructor(private http: HttpClient) { }
}
submitShipment(rShip: ReturnShipment) {
this.http.post(this.shipmentCreation, rShip, httpOptions)
.subscribe(
data => {console.log('AllthePost' + JSON.stringify(data));},
err => {console.log("error occurred");}
);
}
private handleError(handleError: any): import("rxjs").OperatorFunction<any[], any> {
throw new Error("Method not implemented.");
}
}
Upvotes: 0
Views: 2875
Reputation: 1
/**
* Construct a POST request which interprets the body as JSON and returns it.
*
* @return an `Observable` of the body as an `Object`.
*/
post(url: string, body: any | null, options?: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<Object>;
It's weird because http.post returns observable and iis possible to subscribe to it
Upvotes: 0
Reputation: 222582
You should not subscribe within your service, instead subscribe in the component, also return
the http.post from your service
return this.http.post(this.shipmentCreation, rShip, httpOptions)
and your component code should be,
this.shipmentServic.submitShipment(shipObj).subscribe(response => {
});
Upvotes: 2