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?