Angular component unable to access Service provided via Dependency Injection

After diving into an Angular tutorial yesterday (), I reached a point where services came into play.

The Service class, named MediaServiceService and housed in the media-service.service.ts file, had the following structure:

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

@Injectable({
  providedIn: 'root'
})
export class MediaServiceService {

  constructor() { }

    get(){
    return this.mediaItems;
}
add(mediaItem){
    this.mediaItems.push(mediaItem);
}
delete(mediaItem){
    let index = this.mediaItems.indexOf(mediaItem);
    if(index >= 0){
        this.mediaItems.splice(index, 1);
    }
}

mediaItems = [
    {
        id: 1,
        name: "Firebug",
        medium: "Series",
        category: "Science Fiction",
        year: 2010,
        watchedOn: 1294166565384,
        isFavorite: false
    },
    {
        id: 2,
        name: "The Small Tall",
        medium: "Movies",
        category: "Comedy",
        year: 2015,
        watchedOn: null,
        isFavorite: true
    }, {
        id: 3,
        name: "The Redemption",
        medium: "Movies",
        category: "Action",
        year: 2016,
        watchedOn: null,
        isFavorite: false
    }, {
        id: 4,
        name: "Hoopers",
        medium: "Series",
        category: "Drama",
        year: null,
        watchedOn: null,
        isFavorite: true
    }, {
        id: 5,
        name: "Happy Joe: Cheery Road",
        medium: "Movies",
        category: "Action",
        year: 2015,
        watchedOn: 1457166565384,
        isFavorite: false
    }
];
}

Although the tutorial didn't cover the Injectable decorator, I decided to implement it using Angular CLI.

In my app.module.ts file, I imported the service:

import { MediaServiceService } from "./media-service.service";

Then, in the @NgModule decorator's providers metadata property in the same app.module.ts file:

providers: [
  MediaServiceService,
],

The issue arose when I tried to utilize the service in one of my components. Upon importing the service and injecting it through the constructor, the class looked like this:

import {Component, OnInit} from '@angular/core';
import {MediaServiceService} from "../media-service.service";

@Component({
selector: 'app-media-item-list',
templateUrl: './media-item-list.component.html',
styleUrls: ['./media-item-list.component.css']
})
export class MediaItemListComponent implements OnInit{

mediaItems;

constructor(mediaService: MediaServiceService){

}

ngOnInit(): void {
    this.mediaItems = this.mediaService.get();
}

onMediaItemDelete(mediaItem) {
    this.mediaService.delete(mediaItem);
}


}

Despite following proper dependency injection practices, I encountered the error:

TS2339:Property 'mediaService' does not exist on type 'MediaItemListComponent'.

Using PHPStorm as my IDE, I attempted to resolve the issue by restarting it to no avail.

To eliminate the error as suggested, I created a variable named mediaService and assigned the injected MediaService to it within the constructor:

mediaService;
constructor(mediaService: MediaServiceService){
    this.mediaService = mediaService;
}

Although this workaround worked, I remain puzzled as to why it was necessary in this scenario when I hadn't encountered this requirement previously.

Was I overlooking something? Why did my dependency injection not function as expected?

Answer №1

When utilizing the mediaService beyond the constructor, ensure to declare it differently by modifying your constructor to:

constructor(private mediaService: MediaServiceService){

}

Answer №2

It appears that the privacy setting was not added to the constructor:

constructor(private mediaService: MediaServiceService){

}

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

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Display and conceal table columns dynamically in Vue by utilizing the Vuetify data table functionality

Looking for an example: How to show hide columns of vuetify data table using v-select list I have created something similar, but I'm facing an issue where the table doesn't refresh when changing the header data: https://codepen.io/Meff1/pen/vY ...

Upgrading from Angular 4 to 9

What is the recommended approach for migrating from Angular 4 to 9 - should one go directly from 4 to 9, or is it better to first upgrade to version 7 and then to 9? ...

Ways to simulate an initialized class within a function without using dependency injection

Creating a unit test for a service that utilizes aws-sdk to retrieve all files from an s3 bucket poses a challenge. Within the function, the S3 class is instantiated and listObjectsV2 is used to fetch files from the bucket. For testing purposes, it's ...

Error: Axios encountered an issue with resolving the address for the openapi.debank.com endpoint

After executing the ninth command to install debank-open-api, I encountered an error while running the code in my index.js file. To install debank-open-api, I used the following command: npm install debank-open-api --save Upon running the following code ...

The concept of type literals in Typescript provides a powerful tool for achieving function

In TypeScript, I am aiming to create an overloaded function with named parameters. Despite the code running correctly, I encounter warnings about `init.index` potentially not existing in one of the function signatures. The purpose of overloading is to off ...

Troubleshooting problem with fetching data from Angular API

Looking to use Angular to extract a specific value from the following API: Current code snippet being utilized: app.controller("api", function($scope, $http) { $scope.home = "This is the homepage"; $scope.getRequest = function() { console. ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Checking and unchecking checkboxes based on certain conditions

Below are the checkboxes included in app.components.html <mat-checkbox (change)="temperature($bd_submain)">Temperature</mat-checkbox> <mat-checkbox color='primary'>Soil Moisture</mat-checkbox> When the "Temperature" chec ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Mastering the intricacies of Angular bindings through intuition

I am attempting to grasp the concept of distinguishing between square brackets binding <elem [...]="..."><elem> and parentheses binding <elem (...)="..."<elem>. Is there a rule of thumb that can help differentiate between the two? Pe ...

Automatically increase the version with Yarn auto Version Bump

My package.json file uses a 4-digit version format like "version": "1.3.0-0". When I run the command yarn version --prerelease on my Windows system, it correctly shows: info Current version: 1.3.0-0 info New version: 1.3.0-1 However, ...

The variables declared within the Promise constructor are being identified as undefined by Typescript

In my code, I am creating a let variable named resolver which I intend to set within a promise constructor function. interface Request { ids: string[]; resolver: () => void; promise: Promise<unknown> } class Foo { public requests: ...

Display streaming data continuously within an HTML page using Angular 16

Currently, I am actively developing a stream API that receives data with a 'Content-Type' of 'text/event-stream'. Below is a snippet from my stream.service.ts: connectToSse(): Observable<any> { return new Observable((observer ...

Steps for converting an observable http request into a promise request

Here is a link to my service file: https://i.sstatic.net/8dsMx.png This is the TypeScript file for my components: https://i.sstatic.net/of6sx.png And these are the response models: https://i.sstatic.net/U8RUQ.png https://i.sstatic.net/7baTj.png I am curre ...

What is the best method for saving information from a service to a class or interface in Angular 2?

I am currently in the process of developing a new web application and I am fairly inexperienced with Angular2. I am encountering an issue with one of my components that acts as a form for users to update their data. The problem lies in accessing specific ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

Angular 10 library devoid of ivy technology

After successfully building an Angular 10 library and using it via a direct import (file:dist/my-lib), I decided to publish the library to a private npm repository. To accomplish this, I made changes to my tsconfig.lib.json file and disabled ivy: "ang ...

Running a desktop Word AddIn using Angular 11.0.5 on MS Office 2016: A Step-by-Step Guide

I am facing an issue with loading my add-ins in the Office desktop version, although it works fine on the online platform. I initially developed the AddIn using Angular 5.2.11 and it worked perfectly. However, after upgrading to Angular 11.0.5, the Add-in ...

Using ngModel to bind input fields with predefined default values

I have an input field and I'm trying to set default values, but when using ngModel the input fields are coming up empty. How can I set default values that the user can change? <div class="control"> <input #name="ngModel" ...