I have created a simple HTTP requests class using Angular 2:
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())
}
}
I am trying to use it with a file that's bootstrapped:
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 entered in a form
"password": this.password // password entered 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 {
}
})
}
}
However, I keep getting an error from http-handler.ts
: this.http is undefined
. Strangely, when I copy all the methods from http-handler.ts
into login.component.ts
, everything works fine. Any idea what could be causing this issue?