使用Http模块的辅助函数

时间:2017-02-24 19:12:41

标签: angular

我想创建一个使用Http模块发送请求的简单辅助函数。

using UnityEngine;
using System.Collections;

//Add this class to your world game object and store your globals here
public class GlobalContext : MonoBehaviour{
}

public class BaseClass : MonoBehaviour {
    private GlobalContext world;
    void Start() {
        //find the cabinet object in your scene
        world= transform.root.GetComponent<GlobalContext>();
    }
}

但我不知道如何将Http作为依赖注入。

1 个答案:

答案 0 :(得分:5)

我会创建一个扩展Http的HTTP拦截器:

import { Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/finally';
import 'rxjs/add/observable/timer';

export class HttpService extends Http {


    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options));
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.get(url, options));
    }

    post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url, body, options));
    }

    put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.put(url, body, options));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options));
    }


    intercept(observable: Observable<Response>): Observable<Response> {
        return observable

            .finally(() => {
                serverLog(...) <-- log here
            });
    }
}

将其导入您的模块,如下所示:

@NgModule({
    imports: [
        BrowserModule,
        HttpModule
    ],
    declarations: [AppComponent, LoadingComponent],
    providers: [
        {
            provide: Http,
            useFactory: (backend: XHRBackend, options: RequestOptions) => {
                return new HttpService(backend, options);
            },
            deps: [XHRBackend, RequestOptions]
        }
    ],
    bootstrap: [AppComponent],
})
export class AppModule { }