In my Angular 2 project ListingService can\'t get data from server via post. I\'m getting this error:
EXCEPTION: TypeError: Cannot read property \'post\' of
You have to add HTTP_PROVIDERS
to either the component providers
array like this:
providers: [HTTP_PROVIDERS]
or preferably in the bootstrap like this:
bootstrap(AppComponent, [HTTP_PROVIDERS]);
And you are missing the constructor
http injection in the ListingService
:
export class ListingService {
constructor(private http : Http){}
}
addendum
The reason you are not receiving any listings is because you are using a Promise instead of Observable:
in getListings()
in ListingService
return this:
return this.http.post("bla bla").map(res => res.json).map((res) => {
return this.listings = res;
});
then subscribe to this in the getListings()
in the ListingsComponent
:
getListings() {
this.listingService.getListings().subscribe(listings => this.listings = listings);
}
You should return the observable object from your request in the service:
@Injectable()
export class CompanyService {
constructor(http:Http/*, routeParams: RouteParams*/) {
this.http = http;
}
getCompanies() {
return this.http.get('https://angular2.apispark.net/v1/companies/')
.map(res => res.json());
}
}
And subscribe a listener from your component:
export class CompanyList implements OnInit {
public companies: Company[];
constructor(private service: CompanyService) {
this.service = service;
}
ngOnInit() {
this.service.getCompanies().subscribe(
data => this.companies = data);
}
}
Hope it helps you, Thierry