Angular2:导出自定义HTTP请求类

时间:2016-03-16 14:36:21

标签: angular typescript

我用Angular 2编写了一个小的HTTP请求类:

http-handler.ts

import {Http, Headers, RequestOptions} from 'angular2/http'
import {Injectable} from 'angular2/core';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpHandler {

    constructor(private http: Http) { }

    post(url, _body) {
        let body = JSON.stringify(_body);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(url, body, options)
            .toPromise()
            .then(res => res.json())
    }

    get(url) {
        return this.http.get(url)
            .toPromise()
            .then(res => res.json())
    }
}

我想将它与一个引导文件一起使用:

login.component.ts

import {Component} from 'angular2/core';
import {Http, Headers, RequestOptions} from 'angular2/http'

import {HttpRequest} from './http-handler'

import 'rxjs/add/operator/toPromise';

@Component({
    selector: 'loginForm',
    template:`<some html>`,
})

export class LoginComponent extends HttpRequest {

    login(event) {
        var credentials = {
            "username": this.username, // username put in a form
            "password": this.password  // password put in a form
        }

        this.post('http://localhost/login', credentials) // method from http-handler.ts file
            .then(result => {
                if (result.correct) {
                    sessionStorage.setItem('username', this.username);
                    window.location = 'welcome.html';
                    event.preventDefault();
                    return false;
                }
                else {

                }
            })

    }
}

现在,我得到的是来自http-handler.tsthis.http is undefined的错误。当我将所有方法从http-handler.ts粘贴到login.component.ts时,代码完美无缺。你知道什么是错的吗?

1 个答案:

答案 0 :(得分:0)

但是这样做的原因是什么?。

如果您想更改标题,可以执行以下操作。

    export class baseRequestOption extends BaseRequestOptions {

    constructor(private _authService?:AuthService) {
        super();
        var token = this._authService.token;
        if (token) {
            this.headers.set("Authorization", "Bearer " + token);       
            this.headers.set("Content-Type", "application/json");
        } else {            
            this.headers.set("Content-Type", "application/json");
        }

    }
}
@Injectable()
export class BaseHttpService {

	http: Http;
	constructor(http: Http,private _authService:AuthService) {
        this.http = http;
        this.http._defaultOptions = new baseRequestOption(this._authService);

	}

}

`