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

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Tips for sending an array of any type to a Lookup function

I'm currently utilizing ngl-lookup from the ngl-lightning library and I'm attempting to pass an array of type any[] instead of String[]. Here's the code snippet I have: <ngl-lookup [lookup]="lookupManagerUsers" [icon]="true" [image]="&a ...

Effortless column organization with Bootstrap

My goal is to simplify my column arrangement based on a boolean value. If the value is false <div class="row"> <div class="col-4">A</div> <div class="col-4">B</div> ...

Verify internet connectivity with Ionic

Seeking a reliable method to accurately detect whether a mobile device is truly online and connected to the internet. One approach I have explored involves utilizing an http interceptor: if (navigator.connection.type != Connection.NONE) alert("you'r ...

What is the best way to organize my NPM package with separate directories for types and functions?

I am currently working on developing a custom NPM package that will serve as a repository for sharing types and functions across my project. Let's name this project wordle. Given the emphasis on types, it is worth noting that I am using TypeScript for ...

How to retrieve Angular directive name using TypeScript

I have successfully implemented the following AngularJS directive: export module Directives { export class PasswordsMatch implements ng.IDirective { public static Factory(name: string) : ng.IDirectiveFactory { return () => new ...

What is the Vue.js equivalent of Angular's ng-container?

When working with Angular, you may come across a tag called ng-container which is used in the following way: <ng-container *ngIf="false">this won't be shown</ng-container> According to the Angular documentation: The Angular is a grou ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

Understanding the process of reading cookies on the Angular2 side that have been set by the C# server

I'm struggling to understand how the angular code can access the cookie that was set on the server side. I found the following code snippet on GitHub. This C# function sets the cookie in the Response object with the last line of code. My question is, ...

Tips for accessing data from a JSON file in a compiled Angular2 project

I have a scenario in my Angular2 project where I am fetching settings from a JSON file. However, after compiling the project for production using the ng build command, I noticed that the content of the JSON file is now inserted into the main.bundle.js. Thi ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

Injecting dependencies in Angular into an exported function

After diving into the world of apollo graphql, I stumbled upon a fascinating module housing an intriguing function. export function createApollo(httpLink: HttpLink, connectToDevTools: true){ The heart of this function lies in defining the url for the gra ...

Angular appears to be unresponsive to callbacks

I currently have a small web application that features a wishlist functionality. While adding items to the list works fine, I am facing an issue with the delete operation in Angular. It seems like Angular does not wait for the response before navigating aw ...

Saving any type of file in SQL Server with a field type of varbinary(max) can be achieved by utilizing Angular with ASP.NET Core to create a REST API

I am currently facing an issue while attempting to save a file, such as an image, in the Microsoft SQL Server Management Studio through asp .NET core for the Rest API. I have managed to create a base64 representation of the file, but I am unsure about the ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order. I believe the asynchronous b ...

What is the proper way to create a generic class that can produce various output types while implementing a basic interface?

An abstract class is being created here to transform one type of object into another, with a simple interface comprising id:string and type:string. The intention behind the class definition is to emphasize that it will produce an assembly and during insta ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...