Using $http in the Tour of Heroes Component

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?

Answer №1

When I was searching on Google, I found that most of the articles for Angular were focused on Angular 1. This led me to answers that talked about controllers and other features specific to Angular 1.

Angular 2 is a completely different framework. If you're just starting out, I recommend searching for Angular 2 specifically, so you come across more relevant resources.

If you're using Visual Studio, here's a helpful link to kickstart your Angular 2 and .NET Core web app development:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

Incorporate an image upload feature into the current ajax script

Everything in my code seems to work fine, except for image uploading. It successfully inserts all the data into the database. <input type="file" name="image2" class="file" id="imgInp"/> However, after adding the file input type in PHP, an error mes ...

Struggling with retrieving data from a file in Angular service while using node-webkit. Unable to make it functional

I've been struggling for a while and gone through numerous solutions, but I can't seem to figure out why this code isn't functioning: I have a requirement to pass data between controllers, so I created a service, right? (The data is coming ...

Unexpected behavior: Axios post still enters catch block despite successful completion of Rest API call

Having an issue with my axios post request not returning the value from the API in a non-success scenario (401 error). It works fine for successful scenarios. When using Postman to test the output of my reset password API by providing an incorrect current ...

Access a JSON value in the Google Sheets script editor and retrieve the data

I'm trying to retrieve a value from a JSON object by making an API call in a Google Sheet. Below is the script I am using: function getBitcoinPrice() { var url = "https://acx.io//api/v2/tickers/btcaud.json"; var response = UrlFetchApp.fetc ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

Switch back and forth between multiple functions

It appears that the code provided is not functioning correctly with jQuery versions higher than 1.8. Can anyone offer insight on how to achieve the same functionality with newer versions? Additionally, should we be structuring our code like element.click(f ...

What is the optimal way to update an array within a loop only when a certain condition is met?

I am currently working on a function that will iterate through folders in Google Drive, searching for files (Google Sheets) that match a specific date specified in a table cell. Once a matching file is found, the name of the containing folder is stored in ...

Is there a method in the dir-pagination directive for angularjs that allows me to retrieve all the records from the current page in pagination?

Is there a method to retrieve all records on the current page of the dir-pagination directive by @michaelbromley? If you need assistance, you can refer to this link: dir-pagination, where I am looking to extract a collection of 5 records ranging from 100 ...

What are the steps to access an Alexa skill through a web browser?

I recently developed an Alexa skill for recipe recommendations. I am wondering if it is possible to have the skill open a browser on my phone and display the recipe when I say, "Alexa, send me the recipe"? The skill is working perfectly in the Alexa devel ...

How can I add a group label to search options in "React Select"?

I have implemented a search/filter feature using react-select for users to search through a list of options. However, I am facing an issue where the group labels are not included in the search. I am now exploring ways to incorporate group labels into the s ...

Tips for isolating html and js code?

After following a tutorial to write the program, I attempted to separate the HTML code from JS but encountered issues. Some lines of JS code are connected to the database as parameters, and when I split the HTML and JS codes, it no longer functions. Does ...

Looking to switch up the display of Ionic Infinite Scroll from vertical to horizontal orientation

Recently delving into Ionic Scroll and encountering a challenge. Finding it difficult to arrange content in a horizontal row. To illustrate my issue, I've created a [pen](http://codepen.io/shaikmaqsood/full/zBbREr/ This is the PEN) for better unders ...

"Has the implementation of functions within the Serial API, specifically navigator.serial and SerialPort, not been completed

I’ve been attempting to establish a connection with the serial port through a web page, and it seems that the supported method for this is using the Serial API. var Serial = {}; (function() { 'use strict'; /* * Initiate the Serial ob ...

How to Install MongoDB Using Command Line (Issue: WirdTiger feature not supported in this version of mongod)

I am encountering difficulties with the installation of Mongod on my system. Can someone please clarify what WirdTiger is and provide guidance on resolving this issue? I have already attempted to install MongoDB on my machine and created the Data\db f ...

How is it possible that the SetTimeout code continues to run even after calling clearTimeout

I have this code snippet within my react component: //some code var timeout = null; //global variable //some more code useEffect(() => { if(...some condition) { console.log('test1'); timeout = setTimeout(() => { ...

Conceal the Initial Data Point in a Series on HighCharts

Is there a way to toggle the visibility of specific year columns in a chart using checkboxes? I've tried using the .hide() method but it doesn't seem to work for individual data points within the series. For example, I want to hide the 2018 colum ...

Ways to conceal elements when a webpage is displayed in a pop-up window

JavaScript // Open popup window $('a.popup').click(function(){ window.open( this.href, 'Page title', 'width=600, height=650' ); return false; }); HTML snippet <a class="popup" href="sample.html"> In order to ...

What is the best way to merge shared information within a JSON object while utilizing the Map()

Here is some JSON Data for reference: { "+2555970315763":{ "uid": "u9weKk62GvXu4Yf66HM2TFXDL5S2", "phoneNumber": "+2555970315763", "lastTime": "Mon ...

Generating URL parameters for Ajax requests on the fly

My current project involves creating a dynamic form where the number of fields displayed changes based on the user's selection from a dropdown menu. This means that depending on what option they choose, anywhere from 2 to 20 different fields may be sh ...