Dependency injection in Angular 2 service not functioning as expected

I am facing an issue while trying to retrieve static data from UserService in Angular 2. Although everything seems correct based on the documentation, it is not functioning as expected.

Below is my UserComponent.ts

import {Component ,OnInit } from '@angular/core';
import {UsersService} from './users.service';


    @Component({
      selector: 'users',
      template: `<h3>Users </h3>
      <ul> 
        <li *ngFor="let user of users">{{user}}</li>
      </ul>
       `,
      providers:[UsersService]
    })
    export class UsersComponent {
        users;
        title;

        construct( usersService: UsersService){
           this.users=usersService.getUsers();
// i also tried this but no luck. this.users = this.usersService.getUsers();
        }

    }

And here is my UsersService.ts

import { Injectable } from '@angular/core';
@Injectable()
export class UsersService {
    users =['krishna','ravi','ram','ramesh','sita'];
          getUsers()  {
            return this.users ;
        }

}

The expected output should be:

<h3>Users </h3>
  <ul>  
    <li>Krishna</li>
    <li>Ravi</li>
    <li>Hari</li>
    <li>etc</li>
  </ul>

However, the *ngFor loop is not working as intended. Printing {{users}} returns empty. Any suggestions on what might be causing this issue would be greatly appreciated.

Answer №1

There appears to be a typo in the word constructor

export class UsersComponent {
  users;
  title;

  constructor( private usersService: UsersService) {        
  }

  ngOnInit() {
    this.users = this.usersService.getUsers();
  }
}

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

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

The ngOnChanges method fails to exhibit the anticipated modifications in a variable

Trying to grasp the concept of the ngOnChanges() callback, I created an example below. Despite having values for the attributes title and content in the Post interface during compile time, I do not see any logs from ngOnChanges. Please advise on the corre ...

Definition of TypeScript array properties

Having some trouble creating a type for an array with properties. Can't seem to figure out how to add typings to it, wondering if it's even possible. // Scale of font weights const fontWeights: FontWeights = [300, 400, 500]; // Font weight alia ...

I need to access the link_id value from this specific actionid and then execute the corresponding function within the Ionic framework

I have a JavaScript code in my TypeScript file. It retrieves the attribute from a span element when it is clicked. I want to store this attribute's value in a TypeScript variable and then call a TypeScript function. Take a look at my ngOnInit method, ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

The current context for type 'this' cannot be assigned to the method's 'this' of type '...'

Currently, I am in the process of defining type definitions (.d.ts) for a JavaScript library. In this specific library, one of the methods accepts an object of functions as input, internally utilizes Function.prototype.bind on each function, and then expos ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

How to properly pass a parameter value to an Angular service when using inject.get in the constructor

After experimenting with injecting services in Angular, I encountered an issue when trying to call LogService within GlobalErrorHandler. Despite my best efforts, the code below just wouldn't work. I discovered that the problem stemmed from not passin ...

Is it possible in Typescript to determine whether an object or function was brought in through an "import * as myImport" declaration?

Currently, I am importing all exports from a file in the following way: import * as strings from "../src/string"; After that, I assign a function to a const based on a condition: const decode = (strings._decode) ? strings._decode : strings.decod ...

Cordova's FileReader takes precedence over TypeScript's FileReader functionality

I encountered an issue when adding the cordova-plugin-file-transfer plugin, where I received the error message: reader.addEventListener is not a function. This problem arises due to Cordova FileReader class overriding typescript FileReader. How can this ...

Mastering error handling in Angular's Http requests

In my frontend application using Angular, I need to communicate with a RESTful webservice for the login process. The webservice returns different response codes in JSON format depending on the success or failure of the login attempt: If the login is corre ...

Executing Functions from Imported Modules in Typescript

Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code: import * as mathFn from './formula/math'; export functi ...

Troubleshooting issue with image dimensions in Angular within CKEditor content

One issue I am facing is with CKEditor, where images inserted into Rich Text Fields have their height and width attributes set in a CSS style tag. For example: <img alt="" src="https://something.cloudfront.net/something.jpg" style="height:402px; ...

The ngIf directive in Ionic 2 does not refresh after a user logs in

I'm facing an issue with the *ngIf directive in Ionic 2. Below is my code: <div *ngIf="isLogin" class="profile-info ng-binding padding text-center" (click)="openPage(accountPage)"> {{userEmail}} <span menu-toggle="menu-togg ...

Encountering TypeScript error in the beforeRouteUpdate hook with Vue and vue-property-decorator

I am developing an application using Vue 2 with TypeScript and vue-property-decorator. Within my component, I am utilizing the beforeRouteEnter/beforeRouteUpdate hooks. One of the methods in my component is findProjects, which I want to call within the bef ...

Determine the accurate data type while iterating through a for loop

I am facing an issue where I have around 40 unique actions defined, all with the same parameters except for each being provided with a different schema which is causing the problem type ActionName = 'replaceText' | 'replaceImage'; type ...

The assignment of `accessToken` is restricted in Mapbox-gl's typing

I'm currently utilizing the mapbox-gl library in conjunction with TypeScript. Moreover, I have successfully installed its type definitions that are sourced from the community using @types/mapbox-gl. However, when attempting to import and assign an acc ...

What is the best way to clear a form in a Next.js 13.4 component following a server action?

Currently, I am working on a component using next.js 13.4, typescript, and resend functionality. My code is functioning properly without clearing data from inputs, as it uses the "action" attribute which is commented out. However, I started incorporating ...

Generic Abstract Classes in TypeScript

In my TypeScript code, I have an abstract generic class with a method that takes a parameter of a class type variable. When I tried to implement the abstract method in a derived class, I noticed that the TypeScript compiler doesn't check the type of t ...