httpリクエストを少し簡略化するために、私の友人用の小さなtypescript httpライブラリに取り組んでいます。友人が私が作成したHttp
オブジェクトのメソッドpost()
を使用して非同期POSTリクエストを送信できるようにします。カスタムXHRコールバックハンドラー
私は角度2のsubscribe()
メソッドと同様のことを達成したいと思います。私は、コールバック(成功、エラー、完了の3種類)を担当する関数を作成したいと思います。私のHttpのpost()メソッドここまでは私が今まで持っているものです。
のHttp:基本的にはここに
が書かれたアイデアがある
import { IHeader } from 'interfaces';
import { SubscribeAble } from 'subscribeAble';
class Http {
http: XMLHttpRequest;
constructor() {
this.http = new XMLHttpRequest;
}
post(url: string, data: Object, headers?: Array<IHeader>) {
this.http.open('POST', url);
if(headers) {
for(let header of headers) {
this.http.setRequestHeader(header.name, header.value);
}
}
this.http.send(JSON.stringify(data));
return new SubscribeAble(this.http);
}
}
SubscribeAble:
export class Subscribe {
http: XMLHttpRequest;
constructor(http) {
this.http = http;
}
subscribe(success: (success) => void, error?: (error) => void, complete?:() => void) {
this.http.onload = success;
if(error) { this.http.onerror = error; }
if(complete) { this.http.onreadystatechange = complete; }
}
}
私が今必要なものはsubscribe()
内の関数にデータを挿入する方法のアイデアですメソッド...少し単純です:私は成功の変数this.http.response
の値を持ってほしい(success) => {}
。前もって感謝します。