I am currently facing an issue with my Angular 2 project's Http functionality. I have defined it as a parameter in the constructor, but it keeps printing as undefined. Below is the snippet of code from my project:
import 'rxjs/add/operator/toPromise';
import {Http, HttpModule, RequestOptions, XHRBackend} from "@angular/http";
import { Injectable } from '@angular/core';
@Injectable()
export class GetDataService{
private dataUrl = '/data'; // URL to web API
private req;
//mode = 'observable';
public headers;
public options;
constructor(http:Http) {
//this.http = new Http(XHRBackend, RequestOptions);
console.log(http);
}
}
Here is the error message I am encountering:
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/invoice.component.html:160:0 caused by: Cannot read property 'get' of undefined
Here is the component where the service is used:
import {Component} from '@angular/core';
import {GetDataService} from "./get-data.service";
@Component({
selector: 'http',
template: `<h4>response</h4>`
})
export class GetDataComponent {
response:string;
getDataService:GetDataService;
constructor(){
this.getDataService = new GetDataService();
console.log(this.getDataService.getData());
}
}
And make sure to add the service in the main module providers.
Furthermore, when I attempt to inject GetDataService in the constructor parameter:
constructor(getDataService:GetDataService){
this.getDataService = getDataService;
console.log(this.getDataService.getData());
}
I encounter the following error:
Error: (SystemJS) Can't resolve all parameters for GetDataComponent
I have also tried creating an object of Http inside the constructor, but the error persists:
constructor() {
this.http = new Http;
console.log(this.http);
}
This is the result of the above code:
Http {_backend: undefined, _defaultOptions: undefined}
Any assistance would be greatly appreciated.