Currently, I have the Tour of Heroes application up and running, but now I want to enhance it by making AJAX calls.
I have set up a WebAPI service that delivers the data with CORS enabled. To test this, I created a simple non-Angular client using JQuery $.post and $GetJson, and everything was working smoothly.
Below is my hero-details.component.ts file (I am happy to share any additional files if needed):
import {Component , Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { HttpModule } from '@angular/http';
import 'rxjs/add/operator/switchMap';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls : ['./hero-detail.component.css']
})
export class HeroDetailComponent { // implements OnInit {
@Input() hero: Hero;
powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
submitted = false;
constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location,
$http //**--LINE OF INTEREST #2**
) { }
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
}
save(): void {
this.heroService.update(this.hero)
.then(() => this.goBack());
}
goBack(): void {
this.location.back();
}
onSubmit() { this.submitted = true; }
callService( ) {
var uri = 'http://localhost:61212/api/heros';
//**// LINE OF INTEREST #1**
$http({
method: 'GET',
url: uri
}).then(function () { alert('success'); }, function () { alert('fail');});
};
}
Upon trying to compile, I encounter the following error:
TS2304: Cannot find '$http'
If I comment out the $HTTP call (Line of Interest #1), the code compiles and runs successfully until I reach the function where I declare and assign the variable "uri". This leads me to believe that I have identified the issue accurately.
After extensive research online, I have come to the conclusion that I need to Dependency Inject the $http object into this component.
However, when I attempt to pass $http into the constructor (LINE OF INTEREST #2), I receive the following error during compilation:
TS7006 Parameter '$http' implicitly has an 'any' type
I have been researching this extensively, so much so that Larry and Sergy have asked me to take a break. Although I found examples of $http being injected into controllers, I cannot seem to translate that information into a solution for my specific case.
1) Does injecting the $http object appear to be the correct course of action?
2) If so, what is the appropriate syntax to accomplish this?