2016-12-22 5 views
0

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) => {}。前もって感謝します。

答えて

0

最後にsubscribeメソッドを修復する方法を知りました。私はコールバックを使って私が望むものを達成しました。ここでは、コードは次のとおりです。

subscribe(success: (success) => void, error?: (error) => void, complete?:() => void) { 
    let callback = (cb: (res) => void) { 
     return callback(this.http.response); 
    } 

    this.http.onload =() => { 
     return callback(success); 
    } 
    if(error) { 
     this.http.onerror =() => { 
      return callback(error); 
     } 
    } 
    if(complete) { this.http.onloadend = complete; } 
} 
0

私はあなたがこのような何かを行うことができると思う。

subscribe(success: (success) => void, error?: (error) => void, complete?:() => void) { 
    this.success = success; 
    this.error = error; 
    this.complete = complete; 

    this.http.onload = this.onload; 
    if(error) { this.http.onerror = this.onerror; } 
    if(complete) { this.http.onreadystatechange = this.oncomplete; } 
} 

onload() { 
    if (this.http.status === 200) { 
     this.success(this.response); 
    } else { 
     if (this.error) 
     this.error(this.http.statusText); 
     } 
    } 
} 

ユーザーがクラス変数としてサブスクライブであなたを送る機能を設定し、必要なデータとそれらを呼び出しますそのパラメータとして送信します。

となり、他の2つの関数のonerroroncompleteメソッドを作成することができます