Trying my hand at angular2
, I discovered the necessity of using the subscribe()
method to fetch the results from a get
or post
method:
this.http.post(path, item).subscribe(
(response: Response)=> {console.log(response)},
(error: any)=>{console.log(error)}
);
However, I had the idea of enhancing the subscribe() method by creating a custom version that includes an error callback function with a strongly typed error argument. This would allow us to subscribe to the Observable in the following manner:
this.http.post(path, item).subscribe(
(response: Response)=> {console.log(response)},
(error: HttpError)=>{console.log(error.body)}
);
I defined the structure of HttpError
as shown below:
import { ModelState } from "app/Base/model-state";
import { ModelStateDictionary } from "app/Base/model-state-dictionary";
import { ErrorBody } from "app/Base/error-body";
export class HttpError {
public ok: boolean;
public status: number;
public statusText: string;
public type: number;
public url: string;
public body: ErrorBody;
public static create(error: any): HttpError {
let errorBody: ErrorBody = new ErrorBody();
let body = JSON.parse(error._body)
errorBody.message = body.message == null ? "" : body.message;
errorBody.modelStateDictionary = new ModelStateDictionary();
if (body.modelState != null) {
for (let key in body.modelState) {
let modelState: ModelState = new ModelState();
modelState.Value = key;
for (let value in body.modelState[key]) {
modelState.Error.push(value);
}
errorBody.modelStateDictionary.push(modelState);
}
}
let httpError: HttpError = new HttpError();
httpError.body = errorBody;
httpError.ok = error.ok;
httpError.status = error.status;
httpError.statusText = error.statusText;
httpError.type = error.type;
httpError.url = error.url;
return httpError;
}
}
To handle this conversion and ensure users can benefit from the improved version of subscribe(), I believe I need to invoke the create()
method prior to subscription and transform the Java object error into an instance of HttpError
. It seems like I might need to implement a custom Observable or utilize map()
. As a newcomer to TypeScript
and Reactive programming
, I would appreciate some guidance on how to accomplish this conversion effectively.