The repaired POST will wait for the same object in the response as the sent one.
This is clearly seen from the typescript definitions. Suppose we have a method that will receive an object of type ITypeA , and it will POST it in the URL, for example http://whatever/api/objects . Suppose a REST api returns 201, as well as json with a response object, which can be the same OR DEFFERENT. In our case, suppose the return type is ITypeB . Then our restangular will not be able to use the standard POST from ITypeA and wait for the response of ITypeB , so the following code will not be correct, because it is expected that restangular will receive a response of type ITypeA (the same as the one sent).
public postAnObject(objectToPost: models.ITypeA): ng.IPromise<models.ITypeB> { return this.restangular.all("objects") .post<models.ITypeA>(objectToPost) .then((responseObject: models.ITypeB) => { return responseObject; }, (restangularError: any) => { throw "Error adding object. Status: " + restangularError.status; }); }
This can be resolved using customPOST, so the code above will be correct:
public postAnObject(objectToPost: models.ITypeA): ng.IPromise<models.ITypeB> { return this.restangular.all("objects") .customPOST(objectToPost) .then((restangularizedObjectTypeB: restangular.IElement) => { return restangularizedObjectTypeB.plain(); }, (restangularError: any) => { throw "Error adding object. Status: " + restangularError.status; }); }
There are some great notes:
- Restangular can get the response object in a successful callback (
then part) - If the use of the
.post(objectA) restangular method would expect, if any, a successful callback with a response of the same type as object A. - If you want to publish object A, but get the response object B (different types), use the
.customPOST(objectA) method - IMPORTANT : the response is actually a “restangularized” object that wraps the “real” response object. This means that the answer contains some restatular methods. If you just want the response object to call the
.plain() method in the response, as shown in my second example, where the answer is not actually an ITypeB object, but restangular.IElement
iberodev
source share