Exploring the World of Angular2's RC.1 Dependency Injection

Currently, I am delving into Angular2, but the challenge lies in the fact that every time I come across a helpful tutorial, it does not align with the latest version of Angular2.

Despite this, my current struggle involves attempting to inject a service from one file to another, but I'm unable to replicate what was demonstrated in the tutorial I was following.

For reference, here is the link to the tutorial:

./main.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from "@angular/core";
import {TodoInput} from './todo-input';
import {TodoService} from "./todo-service";

@Component({
    selector: 'my-app',
    directives: [TodoInput],
    template: '<div><todo-input></todo-input></div>'
})

class App{}

bootstrap(App, [TodoService]);

./todo-service.ts

import {Injectable} from "@angular/core";

@Injectable()

export class TodoService {
    todos:string[] = [];
}

./todo-input.ts

import {Component} from "@angular/core";
import {TodoService} from "./todo-service";

@Component({
    selector: 'todo-input',
    template: `<div>
    I'm a todo input
    <input type="text" #myInput>
    <button (mouseover)="onClick($event, myInput.value)">Click me</button>
    </div>`
})

export class TodoInput{
    constructor(todoService:TodoService) {
        console.log(todoService);
    }

    onClick(event, value) {
        console.log(event, value);
    }
}

After encountering an issue and seeing a console message:

EXCEPTION: TypeError: Cannot read property 'query' of null ...

A small modification led to a resolution:

./todo-input.ts

import {Component} from "@angular/core";
import {TodoService} from "./todo-service";

@Component({
    selector: 'todo-input',
    template: `<div>
    I'm a todo input
    <input type="text" #myInput>
    <button (mouseover)="onClick($event, myInput.value)">Click me</button>
    </div>`
})

export class TodoInput{
    constructor() {
        console.log(TodoService);
    }

    onClick(event, value) {
        console.log(event, value);
    }
}

Following this adjustment, a normal object was displayed in the console, without any errors.

SystemJS config

<script>
    (...SystemJS configuration example...)
</script>

Therefore, my query is: Why am I unable to call that service from the constructor argument as shown in the tutorial? Is there a specific step I am overlooking? While the tutorial appears to be comprehensive, I am facing challenges in grasping some fundamental concepts.

Thank you, Tom

Answer №1

Resolved the issue by addressing the TypeScript compiler delivered with PHPStorm. By configuring my tsconfig.json file and running it through npm tsc, everything is now functioning smoothly.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "./public/admin/js/app"
  },
  "exclude": [
    "node_modules",
    "build",
    "vendor",
    "public"
  ]
}

The only remaining uncertainty is how to eliminate compiling errors from the log, which appear to be originating from excluded folders.

Cheers to everyone!

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

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

Definition of union types in JavaScript using Typescript

Looking for assistance in creating a d.ts file for the union-type library found at https://github.com/paldepind/union-type Consider the following union type: let Maybe = Type({ Nothing: [] , Just: [Number] }) I am interested in setting up compi ...

Struggling to implement the Pick utility type alongside the React useState hook

Can anyone explain why I am unable to utilize the Pick utility type in order to select a property from my interface and apply it to type my component's state? This is what my interface looks like: export interface IBooking { ... propertyId: strin ...

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

Writing TypeScript, Vue, and playing around with experimental decorators

After creating a Vue project through Vue-CLI v3.0.0-beta.15, the project runs smoothly when using npm run serve. However, TypeScript displays an error message stating that support for decorators is experimental and subject to change in a future release, bu ...

Angular QR code scanner: Simplifying the process of scanning

Can anyone provide guidance on incorporating a Live QR Scanner into an Angular application? I attempted to use the Zxing library but struggling to find detailed documentation for integration with Angular. Your assistance is greatly appreciated. Thank you ...

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

What is the best way to display the source code of a function in TypeScript?

I am interested in obtaining the source code for my TypeScript function ** written in TypeScript **. Here is the TypeScript code: var fn = function (a:number, b:number) { return a + b; }; console.log("Code: " + fn); This code snippet displays the Ja ...

How can we pass the onClick prop from a child component to a parent component in React with Typescript?

Currently, I am utilizing React along with TypeScript. I am curious about the process of passing an event from the parent component to a child component using props. Here is an example for better understanding: parent.tsx const ParentComponent: React.F ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

How can I implement a dynamic form to display only when there are values available for the specified ID?

https://i.stack.imgur.com/imqYb.pngI am dealing with an object that is coming from the backend, containing template parameters such as "namespace,resources". In some cases, the template parameter value is "null". My goal is to display a form only when ther ...

How to assign a custom validator parameter to a form group in Angular

I'm in a situation where I have a form group and need to validate the end date so it is not earlier than the start date. The challenge here lies in accessing specific fields when the form group is not yet declared. dateFormGroup: this.fb.group({ ...

What is the process for setting up a single button selection using OR logic and multiple button selection using AND logic?

Currently working on implementing button functionality in React for filtering data. The requirement is that when selecting specific criteria, such as bedroom 3 or multiple selections like bedroom 2 and 3, the logic should vary. For instance, selecting bedr ...

How can I create a tickable image grid in Nativescript Angular?

My goal is to create an image grid in a Nativescript Angular App where users can select images and then move to the next page with the selected image IDs or names. I have successfully created the image grid, but I am struggling to make the images tickable ...

Using AsyncPipe within an ngFor loop to display items

What is the best practice for using an AsyncPipe within an ngFor loop to handle asynchronous calls for items in a list? Scenario: Imagine I have an Order object with Products, and I need to display each product's manufacturer. However, the manufactur ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Tips for assigning the 'store_id' value to a variable in Angular 6 within the Ionic4 environment

Trying to retrieve the store_id from the StorageService in Ionic4 (angular 6). Managed to retrieve the store_id using: let id = this.storageService.get('store_id'); id.then(data => { this.store.push(data) }); After pushing it into an ar ...

Creating a responsive d3 gauge chart: A step-by-step guide

Need assistance resizing the d3 gauge chart. Check out the Stackblitz code for reference. I've attempted the following: .attr("preserveAspectRatio", "xMinYMin meet") as well as window.addEventListener("resize", this.draw); ...

Having trouble implementing the ternary operator (?) in TypeScript within a Next.js project

Trying to implement a ternary operator condition within my onClick event in a Next.js application. However, encountering an error indicating that the condition is not returning any value. Seeking assistance with resolving this issue... https://i.stack.img ...

Angular2 checkboxes for filtering data

I'm working with an Angular2 grid that showcases an array of Fabrics, each with its own color or fabric type properties. Right now, all Fabrics are displayed in the grid, but I need to implement a series of checkboxes for color and fabric type, along ...