Exploring Dependency Injection in Angular2: A Comparison of TypeScript Syntax and @Inject Approach

I'm currently working with Angular2 build 2.0.0-alpha.34 and I can't figure out why I'm getting different results from these two code snippets.

The only variation is between using

@Inject(TitleService) titleService
and titleService: TitleService

This snippet works correctly (ES2015 method)

import {Inject, Component, View, bootstrap, NgFor} from 'angular2/angular2';
import {titleComponent} from './components/title';
import {TitleService} from './services/services';

// Annotation section
@Component({
    selector: 'my-app'
})
@View({
    templateUrl: './html/app.html',
    directives: [titleComponent, NgFor]
})
// Component controller
class MyAppComponent {
    titles: Array<Object>;
    constructor(@Inject(TitleService) titleService) {
        console.log(titleService)
        this.titles = titleService.getTitles();
    }
}

bootstrap(MyAppComponent,[TitleService]); 

This code doesn't function properly (TypeScript method), as it never reaches the console.log statement in the constructor, but no error is thrown either

import {Inject, Component, View, bootstrap, NgFor} from 'angular2/angular2';
import {titleComponent} from './components/title';
import {TitleService} from './services/services';

// Annotation section
@Component({
    selector: 'my-app'
})
@View({
    templateUrl: './html/app.html',
    directives: [titleComponent, NgFor]
})
// Component controller
class MyAppComponent {
    titles: Array<Object>;
    constructor(titleService: TitleService) {
        console.log(titleService)
        this.titles = titleService.getTitles();
    }
}

bootstrap(MyAppComponent,[TitleService]); 

If I opt for TypeScript's injection method, is there something else I need to do elsewhere?

Answer №1

To include the TitleService in your Component annotation, you should add it to the viewBindings section:

viewBindings: [TitleService]

It's important to note that you only need to declare this once, typically in the Root component. Subsequent components within the hierarchy will automatically have access to it from the root component. If a component's injector is unable to resolve the dependency, it will search upwards until it finds it. By defining one viewBindings, the same instance will be available everywhere.

edit: Parameter renaming introduced in alpha 34.

Answer №2

Initially, I had the TitleService concept outlined within a JavaScript file simply utilizing an ES2015 class. After realizing it needed to be converted into a TypeScript file for proper compilation, I made the necessary adjustments. Lesson learned!

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

Developing an Angular 2 MVC project using Visual Studio 2017 with a TFS build server in an offline environment, without internet access and relying

Our ultimate objective is to establish an Angular 2 app using our infrastructure, enabling our development team to collaborate and deploy it to production. We have been seeking solutions to various issues for the past two weeks related to this task, but u ...

Integrating d3.js into an Angular 2 project

Trying to incorporate the d3.js library into a MEAN application using angular2. Here are the steps I've taken: npm install d3 tsd install d3 In mypage.ts file (where I intend to show the d3.js graph) // <reference path="../../../typings/d3/d3.d ...

Encountering a problem during the installation of angular-route.d.ts

When trying to install angular-route using the command typings install angular-route --save -global, I encountered an error. Can someone help me resolve this issue? typings ERR! message Unable to find "angular-route" ("npm") in the registry. typings ERR! ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Having difficulty setting up Firebase Callable Function Emulator configuration

Currently, I am integrating callable functions into an existing Angular/Firebase project. Despite following what I believe to be the correct configuration standards, the project is still accessing the production endpoints, resulting in a CORS exception. H ...

Expired URL in Ionic 3 Navigation

I'm a novice at using Ionic. I recently started my first project about a month ago and it's nearing completion. However, I noticed that whenever I run ionic serve, my app always defaults to localhost:8100. For example, when I land on the home pa ...

Creating a TypeScript function that automatically infers the type of the returned function using generics

Suppose I want to execute the generateFunction() method which will yield the following function: // The returned function const suppliedFunction = <T>(args: T) => { return true; }; // The returned function // This is how it can be used suppli ...

There was an issue with the specified entry-point "auth0/angular-jwt" as it is missing required dependencies

I am currently working on an Angular project with the following versions: @angular-devkit/architect 0.901.1 @angular-devkit/core 9.1.1 @angular-devkit/schematics 9.1.1 @schematics/angular 9.1.1 @schematics/update 0.901.1 rx ...

What is the best way to make a class available in the global namespace within a TypeScript module?

The Issue at Hand Given an existing application with a mixture of modules and global scripts, the goal is to convert one class in a global script (gamma.ts) into a module. This entails adding `export default` before `class gamma {}` in gamma.ts. Additiona ...

Is the calculated sum displaying correctly in HTML but not being saved to Firebase?

When it comes to calculating the sum in HTML, I've found success with the following code snippet: <ion-item type="text" formControlName="billValue" [(ngModel)]="retailerItemModel" name="billValue" ngDefaultControl >Total Bill Value Rs. {{ tot ...

Optimizing Angular 2's Efficiency: A Deep Dive into Change Detection and Performance Metrics (1000 calls measured

As a newcomer to Angular 2, I recently inherited a project using the framework. Upon assessing the app's performance, I noticed it was running quite slowly and causing issues. I investigated further and discovered that many ngIf's and ngFor&apo ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button. You can find mo ...

Unwrapping the Angular ngForm Mystery: Resolving

I was attempting to retrieve values using ngOnInit and initializing the form with default values, but for some reason the form is returning as undefined. I also tried using patchValue, but since the form is undefined, it doesn't work. It's intere ...

Obtain the directive's reference that is being utilized within a component

In one of my components, the template is structured as follows: <div [my-custom-directive]>Some content here</div> Currently, I am trying to access the instance of the MyCustomDirective class being used in this template. Typically, for access ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

Issues with NativeScript WebView displaying HTML file

Having trouble loading a local HTML file into a webview in my NativeScript (typescript) application. Despite using the correct path, it's not loading and instead shows an error. <WebView src="~/assets/content.html" /> An error message stati ...

Unable to perform the upgrade to Angular 6 due to an invalid range

I'm in the process of upgrading to Angular 6 As I follow the upgrade guide, I run into this issue: > ng update @angular/core Invalid range: ">=2.1.0" That's all the information I have. There are no additional warnings or ...

Implementing chance.js in an Angular 4.x Component's ngOnInit() Method

I just started using angular 4.x and I'm trying to load change.js in the ngOnInit() function. I've attempted a few things but nothing seems to be working. Here is the code snippet: This is the code I have so far: import { Component, OnInit, In ...

Overuse of memory and CPU causing performance issues in NgRx and Redux dev tools

Recently, I joined a new project that utilizes Angular and Redux. To my surprise, the Chrome DevTools for Redux were not enabled as it was commented out in the app.module.ts file. I decided to uncomment this section: StoreDevToolsModule.instrument({ n ...