我正在尝试angular2
。我发现我们应该使用subscribe()
方法来检索get
或post
方法的结果:
this.http.post(path, item).subscribe(
(response: Response)=> {console.log(response)},
(error: any)=>{console.log(error)}
);
但是我想创建一个自定义版本的subscribe()方法,它有一个错误回调函数,它的错误参数不是any
并且是强类型的。因此,我们将能够以这种方式订阅Observable:
this.http.post(path, item).subscribe(
(response: Response)=> {console.log(response)},
(error: HttpError)=>{console.log(error.body)}
);
我声明HttpError
如下:
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;
}
}
但在某些地方我需要在订阅之前调用create()
方法,并将java对象错误转换为HttpError
。我想我需要创建一个自定义的Observable,或者可以使用map()
。我是TypeScript
和Reactive programming
的新手。能否请您解释一下如何进行此转换,因此用户可以使用更好的subscribe()版本?
答案 0 :(得分:1)
首先,我相信Angular中的http.post只是封装了HTTP响应。以下是Angular源代码。
function httpRequest(backend: ConnectionBackend, request: Request): Observable<Response> {
return backend.createConnection(request).response;
}
此处,响应或错误实际上是HTTP响应对象。
this.http.post(path, item).subscribe(
(response: Response)=> {console.log(response)},
(error: any)=>{console.log(error)}
);
我认为您可以在Observable中扩展您想要的方法来处理响应并获取定义的Object。类似于this.http.post(path,item).castHttpError()。subscribe()
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/subscribe.md
但是,我不确定这是否安全,因为您正在扩展可靠的库。至少,Angular不建议开发人员创建他/她自己的Angular分发版。你可以尝试一下。
最后,我建议你编写一个实用程序方法来实现它,这可能是多余的但不会有害。
this.http.post(path, item).subscribe(
response => { console.log(response); },
error => {
console.log(toHttpError(error).body);
}
);