Encountering errors with dependency injection in Angular 2 constructors

Recently delving into Angular2, I diligently studied all the tutorials on the official website and eagerly started working on my project. However, I hit a roadblock almost immediately.

Here are the snippets of code:

app.ts:

import { Component }            from '@angular/core';
import { bootstrap }            from '@angular/platform-browser-dynamic';
import { ApiClient }            from './services/api-client';

@Component({
  selector: 'app',
  template: 'Hello',
  providers: [ApiClient]
})
export class AppComponent { constructor(private apiClient: ApiClient) { } }

bootstrap(AppComponent);

api-client.ts:

import { Injectable } from '@angular/core'

@Injectable()
export class ApiClient {
    public login(username: string, password: string, rememberMe: boolean) : boolean {
    if (username == 'testuser' && password == 'password')
        return true;
    else
        return false;
}
}

However, this seemingly straightforward code snippet throws a perplexing exception: EXCEPTION: Error: Uncaught (in promise): TypeError: dep is null

If I remove constructor DI then the exception disappears.

I've been grappling with this issue for the past 4 hours, but to no avail. It's frustrating how the exception message provides no useful information.

Thank you in advance for any assistance.

UPDATE

Referring to the constructor DI, I encountered this:

constructor(private apiClient: ApiClient) { }

Update 2

After replacing Injectable() with Component({}), the code now functions flawlessly. What could this indicate? Could it be an issue with my local Angular2 setup or perhaps some configuration mishap?

Answer №1

Consider trying this:

    import { Component, Inject } from '@angular/core';

...
    export class AppComponent { 

         constructor(@Inject(ApiClient) apiClient: ApiClient) { } 
    }

You may want to include the constructor code for your ApiClient class as well.

Answer №2

Resolved the issue!

It seems that the "node_modules\es6-shim" was mistakenly removed!

Surprisingly, Firefox didn't alert me about this missing file. Fortunately, when I ran the web app in Chrome, I received a warning about the JS reference being absent.

After running "npm install es6-shim," everything is now functioning correctly!

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

The TS-Mocha and Chai duo have encountered a hitch: a peculiar error message, TS2695, informing them that the left side of the

Software Versions: "ts-mocha": "^8.0.0", "ts-node": "^10.3.0", "chai": "^4.3.4", Sample Code: expect(wrapper.find(MyListItem)).to.have.length(3); Execution Command: ts-mocha tests/**/*.tsx -r u ...

The error message "TypeError: render is not a function" is encountered when attempting to call and display information

I am currently working on a movie app using React JS and I encountered an error while trying to render a component based on API data. TypeError: Render is not a function The code works perfectly fine for TvListProvider, but I'm facing this error wi ...

The attribute 'split' is not found on the never data type

I have a function that can update a variable called `result`. If `result` is not a string, the function will stop. However, if it is a string, I then apply the `split()` method to the `result` string. This function always runs successfully without crashin ...

Tips for providing a base URL in Angular to fetch images from an API

How do I access the API URL to retrieve images from a database? <table class="table"> <tr> <th>Id</th> <th>Image</th> </tr> ...

Maintain your position on the current page when refreshing Angular 4

My Anuglar 4 application features multiple routes, with two main ones being Logging and List of items. Specifically, the routes are http://localhost:4200/#/ and http://localhost:4200/#/items. However, I've noticed that when I reload the page while on ...

Step-by-step guide on setting up a personalized validation using Formly alongside a calendar input

I have successfully implemented a custom calendar template, but I am struggling with creating validators and error messages. Most examples I found online deal with input elements, whereas my element is not an input. app.modules.ts FormlyModule.forRoot({ e ...

TYPESCRIPT: The argument labeled as 'typeof X' cannot be assigned to the parameter labeled as 'Y' that extends

As I venture into coding with TypeScript, I am encountering some compilation issues. It appears that I am facing a hierarchy problem with several classes. The first class (A) defines a set of properties/functions. The second class (B) inherits from class ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

Angular 4 project encountered a running error with the following issue displayed

While developing an Angular 4 app in Visual Studio within the same solution as the backend, everything was running fine. However, after adding some services and installing the Moment package, I encountered the following error: I attempted to reinstall pa ...

Passing a click event from a route-outlet to app.component in Angular 2

I'm brand new to using Angular 2 and developing an application app.routing.ts const appRoutes: Routes = [ {path:'', component:HomeComponent}, { path: 'login', component: LoginComponent }, { path: 'register&ap ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

Switch the sidebar position to the right in the ngx-admin interface created by Nebular

I need to customize ngx-admin to display in RTL style with the sidebar on the right. Despite conducting research, I have been unable to find a solution within this Github project. Can anyone offer assistance with this issue? ...

Revamping the *ngIf Container

Seeking a more efficient way to refactor the code snippet below: <div class="container"> <icon class="icon" *ngIf="A || B"></icon> <div class="itemOne" *ngIf="A"></div> <div class="itemTwo" *ngIf="B"></di ...

Using the ternary operator in React to implement inline styles

Within my React/Typescript project, I aim to dynamically exhibit a color based on the presence or absence of a value in payload[1]. In the code snippet below, note the usage of an inline style tag. <li className="recharts-tooltip-item" style={ ...

Enabling or disabling a button dynamically in Ionic based on a conditional statement

I am looking to dynamically enable or disable buttons based on specific conditions. The data is retrieved from Firebase, and depending on the data, I will either enable or disable the button. For example, if a user passes the First Quiz, I want to enable ...

"Discrepancies in behavior observed in Bootstrap JavaScript module when using ng serve versus ng

In my Angular application, I've incorporated the Bootstrap 5.3 JavaScript module by properly installing it with npm i bootstrap and npm i @types/bootstrap. This also led to JQuery and Popper.js being automatically installed. During development while ...

Utilizing Shadow Root and Native Web Components for Seamless In-Page Linking

An illustration of this issue is the <foot-note> custom web component that was developed for my new website, fanaro.io. Normally, in-page linking involves assigning an id to a specific element and then using an <a> with href="#id_name&quo ...

Setting text in a datetime picker with ngx-mat-datetime-picker in an Angular application is a straightforward process

I've been utilizing the ngx-mat-datetime-picker library from angular-material-components to enable datetime selection. It's functioning effectively, but I'm searching for a way to insert text preceding the hour and minute inputs, such as &ap ...

Troubleshooting Problem with Angular 2 Jquery Plugin Upon Returning to Page

I am utilizing the Seriously plugin to present HTML videos on a canvas element. Everything works perfectly during the initial visit to the page, but upon returning, all the videos vanish without any console errors. import {Component, ViewChi ...