A
A
Alex2016-05-13 13:59:29
Angular
Alex, 2016-05-13 13:59:29

How to Angular2 service inject Http&?

Created a simple service in Angular2.
I can't figure out how to inject Http into it.

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

@Injectable()
export class Test{ 

constructor(_http: Http) {
 this._http = _http;
}

getData = function() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://127.0.0.1:8085/', '{blabla}', options)
.map(DATA => DATA.json());
}

}

Error
cannot read property post of undefined
Although in the component this code works with a bang:
import {Component} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Headers, RequestOptions} from 'angular2/http';
import 'rxjs/Rx';

@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
styleUrls: ['app/app.component.css'],
viewProviders: [HTTP_PROVIDERS],
})
export class AppComponent{
constructor(http: Http) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
http.post('http://127.0.0.1:8085/', '{blabla}', options)
.map(DATA => DATA.json()).subscribe(DATA => {
this.Test = DATA.data;
}
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-05-13
@streetflush

Angular2 http.get example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question