Can child directives in Angular 2 harness the power of parent providers?

I am facing an issue while trying to utilize a service as a provider for general use in a Directive rather than a Component. The problem arises when the service is not being received in the child Directive, despite my expectation to use it within the directive:

// CurrentTimeService.ts
import { Injectable } from '@angular/core'

@Injectable()
export class CurrentTimeService {
  dt: number;

  constructor() {
    this.dt = new Date().getTime();
  }


}

app.ts
//our root app component
import {Component} from '@angular/core'
import {CurrentTimeService} from "./CurrentTimeService"
import {SimpleDirective} from "./SimpleDirective"

@Component({
  selector: 'my-app',
  providers: [CurrentTimeService],
  template: `
    <div>
      <h2 mySimpleDirective>Hello {{name}}</h2>

    </div>
  `,
  directives: [SimpleDirective]
})
export class App {
  constructor() {
    this.name = 'Angular 2 (Release Candidate!)'
  }
}

SimpleDirective.ts
import {Directive} from '@angular/core';
import { CurrentTimeService  } from "./currentTimeService"

@Directive({
    selector: '[mySimpleDirective]'
})
export class SimpleDirective {
  constructor(private currentTimeService: CurrentTimeService) {


  }

}

You can view the complete program on Plunker by following this link: https://plnkr.co/edit/s0zUkI?p=preview

Thank you for your help in advance.

Answer №1

Your SimpleDirective.ts file contains an incorrect import statement. Update it as follows:

import { CurrentTimeService  } from "./currentTimeService"

Change it to:

import { CurrentTimeService  } from "./CurrentTimeService"

For a working example, check out this Plunker demo

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

Using Jimp to load a font and retrieve its Base64 representation

I am currently working in Angular with Jimp, attempting to overlay text onto an existing image. However, the image is not updating as expected. const Jimp = require('jimp') var _this = this; Jimp.read("assets/TimeLine.png").then(function ( ...

Navigating through concealed pathways

I have defined the following simple route configuration: const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', component: WidgetComponent }, { path: 'P3', comp ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Navigating the store in Ionic Angular using Ngrx

Currently, I am in the process of developing an app using Ionic Angular Cordova. My issue lies in trying to display the state of my application, specifically all the objects within it. However, despite my efforts, the objects that I have added cannot be lo ...

Ensuring a component is included in a module or nesting a component within a template

Struggling with Angular (not AngularJS) and facing an issue where my template is not referencing components correctly. It seems like the component is not being recognized, either due to incorrect declaration or importing in the right place. I need guidanc ...

Retrieve the Ionic storage item as a string

My issue is related to the code snippet below: this.storage.get('user') Upon execution, it returns the following object: t {__zone_symbol__state: null, __zone_symbol__value: Array(0)} I am uncertain about how to handle this object. Is there ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

Personalized prefix for Angular and WebStorm components

After starting a project in Angular with Visual Studio Code a few months ago, I decided to switch to WebStorm and upgraded the project to Angular 4.0 today. Although my project is running smoothly without any errors, I encountered an issue in WebStorm: ...

Issue with Angular Router: unable to retrieve route parameters in child paths

Within our main app.component routing, we have the following setup: { path: 'store', loadChildren: './store/store.module#StoreModule', canActivate: [LoginGuard] }, Then, in the module, our routes are defined as follows: const routes: ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

Failed to load module chunk: Please update to angular 7

I am encountering an issue with my application hosted on IIS after upgrading to Angular 7. The error message "Loading chunk module failed" indicates that instead of fetching files from the dist/ folder, it is attempting to fetch them from the root folder. ...

How do I implement data range filtering in Typescript?

Seeking assistance with filtering data by date range and forwarding the results to the client. The objective is to extract tickets created within specific dates, but I keep encountering a console error which is proving challenging to resolve. var befor ...

What is the best way to select and style individual HTML elements using CSS?

Having trouble editing a Validations Form in Ionic 4 with CSS. It seems that only the form elements are targeted after clicking on the form group. Attached below are the form states before and after click. I'm unable to style the form elements before ...

Encountering an issue with installing an angular 2 directive, getting a error message "Cannot read property '0' of

I am attempting to install this using the command prompt like so: PS C:\Users\moshel\Workspaces\Aman.Magar.Maply\WebUI> npm install @ngui/auto-complete --save However, I am receiving the following outcome: npm WARN @angular/[ ...

Mocking a service dependency in Angular using Jest and Spectator during testing of a different

I am currently using: Angular CLI: 10.2.3 Node: 12.22.1 Everything is working fine with the project build and execution. I am now focusing on adding tests using Jest and Spectator. Specifically, I'm attempting to test a basic service where I can mo ...

Enhance the functionality of a module by incorporating plugins when Typescript definitions are divided into multiple files

During my exploration of Typescript 2.2, I encountered a challenge in defining a module for HapiJS with various plugin options. To streamline the core code, I split it into multiple .d.ts files and then imported and re-exported them all from the index.d.t ...

Using Angular in conjunction with Azure Durable Functions to implement a retry mechanism for HTTP responses

In my Angular 10 application, I am attempting to integrate Azure Functions. The key is to simplify the Azure function protocol by using a single Observable. Executing an Azure function requires the following steps: Initiate a POST request to the Azure fu ...

Attempting to modify read-only properties is prohibited in strict mode within the context of [background: url({{XXX}}) no-repeat center center

I encountered an issue in Edge, but everything works fine in Chrome. I can't figure out what's causing the problem... <div class="container-fluid project_img" style="background: url({{_project.images.web}}) no-repeat center center;"> ...

`Is there a way to maintain my AWS Amplify login credentials while executing Cypress tests?`

At the moment, I am using a beforeEach() function to log Cypress in before each test. However, this setup is causing some delays. Is there a way for me to keep the user logged in between tests? My main objective is to navigate through all the pages as the ...

In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a compone ...