Unable to retrieve information from service using Angular 1.6 and TypeScript

I'm having an issue retrieving data from a Service in my Controller. Here is the code for my Service file:

import {IHttpService} from 'Angular';

export class MyService {
public static $inject = ['$http'];
constructor(private $http:IHttpService, private getItems){

this.getItems= function() {
  this.$http.get('items.json').then(function(response){
    if(err){
      console.error(err);
    }
    console.log(response.data);
    return response.data;
  });
}}}

And here is the code for the Controller:

import {MyService} from './MyService';
export class MyController {
public:getData;
static inject: Array<string> = ['$http', '$scope', 'MyService'];
constructor(private $http:ng.IHttpService, private $scope:any, private MyService:any){
    this.getData = function(){
      MyService.getItems.then(function (data) {
      this.getItems = data;

      console.log(data);
    });
  }

}

Could someone please help me understand what's going wrong with my code? Thank you.

Answer №1

To retrieve the promise within the getItems function, it should look like this:

this.getItems = function() {
  return this.$http.get('items.json').then(function(response) {
    if(err) {
      console.error(err);
    }
    console.log(response.data);
    return response.data;
  });
}}}

Answer №2

To maintain the context of the class, it is important to update the function declaration as shown below or use an Arrow function. Additionally, ensure that the getItems method returns a $http promise so that you can chain .then method over it.

getItems() {
  //return promise here.
  return this.$http.get('items.json').then((response) => {
    if(err){
      console.error(err);
    }
    console.log(response.data);
    //returning data to chained promise.
    return response.data;
  });
}

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

Exploring the Differences Between Angular 2 Two-Way Data Binding and One-Way

My query pertains to the distinction between Angular 2's two-way and one-way data binding mechanisms. From my understanding, one-way data binding involves data flowing strictly from parent to child. However, this changes when the source of the binding ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Incorporating and modifying a component's aesthetics using styled-components: A comprehensive guide

My OverviewItem component has 2 props and is a styled-component. I want to change just one style on this component, which can be done by using the technique of styling any component. Does creating a wrapper component remain the only option for sharing st ...

Property 'map' is not recognized on type 'Object' and needs to be addressed

I am currently using Angular CLI: 6.0.8 and have implemented the service shown below. However, my code editor's linter keeps showing an error message that reads: [ts] Property 'map' does not exist on type 'Object'. any The error ...

What is the best way to include a Web Service within an export variable in Angular 2 using TypeScript?

Is there a way to incorporate JSON data retrieved from the server into the export var HEROES: Hero[ ] function? Here is the link: https://angular.io/resources/live-examples/toh-5/ts/eplnkr.html In app/mock-heroes.ts, you will find the following data, im ...

What is the best way to incorporate a WYSIWYG Text Area into a TypeScript/Angular2/Bootstrap project?

Does anyone know of a WYSIWYG text editor for TypeScript that is free to use? I've been looking tirelessly but haven't found one that meets my needs. Any recommendations or links would be greatly appreciated. Thank you in advance! ...

Guide on how to prevent click events when a checkbox is not selected in Angular 2

A click event is being used on a ul element with a checkbox below it. When the checkbox is checked, the list should be enabled and the click event should work. If the checkbox is unchecked, the list should be disabled and the click event should not work. ...

Troubleshooting the issue of AngularJS not properly watching an object within a form

Can you please help me understand why this code isn't functioning as expected? I am trying to see the changes made to the user object in the controller. <!doctype html> <html ng-app="myApp"> <head> <meta charset="utf ...

Exception encountered while trying to map JSON data

I am encountering an issue while attempting to send JSON data to my JAVA class. "Failed executing POST IntakeFormSections/PostData: org.jboss.resteasy.spi.ReaderException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of org. ...

How can AngularJS utilize ng-repeat and ng-bind-html to display arrays of HTML strings?

I'm currently attempting to display HTML strings from an array of HTML strings in my AngularJS project. As a newcomer to AngularJS, I have been trying to follow the examples provided on the official AngularJS website, but I am struggling to find a sui ...

Objects within the Prototype in Javascript

While delving into the world of AngularJS, I stumbled upon an interesting revelation - when objects are placed in a prototype object, any instances inheriting from that prototype will alter the prototype's objects upon assignment. For example: funct ...

leveraging angular service with ionic framework

(function () { 'use strict'; angular .module('app') .factory('UserService', UserService); UserService.$inject = ['$http']; function UserService($http) { var service = {}; ...

Using AngularJS to create interactive popups within leaflet maps

My map uses leafletjs to create markers such as ev124, ev125, and so on. In addition, there are links with a key attribute like <a ng-click="popup(evsi)" key="124">link</a> Using angular, I extract the key value this way: $scope.popup= funct ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...

Encountering NodeJS server issues with 505/404 errors while fetching partials

I am currently working on an application built using the M.E.A.N stack. For routing, I have implemented Angular Ui Router. However, I am encountering difficulties in correctly routing partials. The link for the main view is functioning properly with the ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

I am experiencing issues with md-no-focus-style not functioning correctly in my configuration

I have a button that triggers the opening of my navigation bar: https://i.sstatic.net/nMr0i.jpg When I click on it, a hitmarker appears: https://i.sstatic.net/OLQaE.jpg The issue is that even after clicking on a navigation item and transitioning to the ...

Unfortunately, the utilization of an import statement outside a module is restricted when working with Electron

Is there a solution to the well-known problem of encountering the error message "Cannot use import statement outside a module" when working with an Electron-React-Typescript application? //const { app, BrowserWindow } = require('electron'); impor ...