Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter.

Below is my module setup:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule ],
  declarations: [ AppComponent, SearchComponent, ArtistComponent, AlbumComponent, TrackComponent ],
  bootstrap:    [ AppComponent ],
  providers: [{
    provide:SpotifyService,
    deps: [Http], useFactory(http:Http){
        return new SpotifyService(http);
    }}]
})
export class AppModule { }

and this is the structure of the service:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { from, Observable, throwError } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';

@Injectable()
export class SpotifyService {

  constructor(public http: Http) { }

  searchTrack(query:string){
    let params:string = [
      `q=${query}`,
      `type=track`
    ].join("&");

    let queryUrl:string = `https://api.spotify.com/v1/search?${params}`;

    return this.http.request(queryUrl).
pipe(map((e)=> e.json()),
      catchError((e:Response)=> throwError(e)));
  }

}

Here is the definition of the Search component:

export class SearchComponent implements OnInit {
  query:string;
  results: Object;
  constructor(private spotify: SpotifyService,
  private router: Router,
  private route: ActivatedRoute) { 
    this.route.queryParams.subscribe(params=>{
      this.query = params["query"] || "";
    });
  }
}//etc...

However, when running the application, I encounter a blank screen with the error

Error: StaticInjectorError(AppModule)

You can view the StackBlitz example here: https://stackblitz.com/edit/angular-spotify-ngbook

Answer №1

  modules: [{
    module: SpotifyModule,
    dependencies: [HttpClient], useFactory(http: HttpClient){
        return new SpotifyModule(http);
    }}]

Why are you using a factory to declare it?
Simply include it like modules: [SpotifyModule] and let dependency injection handle the rest for you. Also, make sure to properly import HttpClientModule and RouterModule.

imports:      [ BrowserModule, FormsModule, RouterModule.forRoot([]), HttpClientModule ]

Ensure to define valid routes as well.

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

"Implemented a fresh pathway within the app-routing.module.ts file, but unfortunately, ngxAdmin is experiencing functionality issues

While customizing the ngx-admin template, I attempted to incorporate a new module into the app module and added its route in app-routing.module.ts. However, upon trying to open it, the module seems to be stuck at loading without any errors appearing in the ...

During the installation of npm in my angular project directory, an error occurred

Encountered an error while installing packages (npm)...npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Received an invalid response when trying to fetch https://registry.npmjs.org/@babel%2fplugin-proposal-nullish-coalesc ...

"I am looking to retrieve the properties of an object that belongs to the EChartsOption type in TypeScript when working with Angular and ECharts. How

Currently, I am exploring how to access a property of an EChartOptions object in Angular 16.0.2, which may be undefined as I am still new to TypeScript. List of npm packages: eapp/src$ npm list <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

The placeholder text in the matInput field is not being displayed

As a newcomer to Angular, I am facing a challenge that has left me unable to find a solution. Below is the code snippet in question: <mat-form-field> <input matInput placeholder="ZIP" style="color:red;"> </mat-form-field& ...

The symbol 'submitted' has not been declared

I have been working on implementing client-side validation in Angular using ReactiveForms. I encountered an error stating "Identifier 'submitted' is not defined. 'FormGroup' does not contain such a member" on this line: <div *ngIf=&q ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Anticipating outcome in NgRx Effects

Incorporating ngrx-effects into my project has been successful for retrieving data: component dispatches action -> effect triggers http service call -> data is returned from http service -> effect sends data to store through action -> component ...

unable to connect a value with the radio button

I am struggling to incorporate a radio group within a list of items. I am facing difficulty in setting the radio button as checked based on the value provided. Can anyone provide me with some guidance? Here is the HTML code snippet: <div *ngFor=" ...

`Is it possible to animate the rotation of an image within an input control?`

After coming across this helpful answer, I successfully added a rotating GIF image as an icon inside an INPUT control on its right side. Simply applying the "busy" class to my control did the trick, and now it looks like it's in progress. input.busy { ...

Using variables within the useEffect hook in ReactJS

I am currently working on a project using Reactjs with Nextjs. I am facing an issue where I need to retrieve the value of "Editor" and alert it inside the handleSubmit function. Can anyone help me with how to achieve this? Here is my code snippet, any as ...

Displaying index.html exclusively using Angular Capacitor

I am currently working on converting my Angular application into an Android application using Capacitor. I have successfully installed Capacitor in my Angular project, which includes routing functionality. Here are the versions of the tools I am using: &qu ...

Angular 11 issue: Unable to display image on the webpage

When I try to view my image by directly using the URL in the src tag, it works fine. However, when I attempt to load it dynamically, an error is thrown. Even using [src]="img.ImagePath" method gives me the same response Here is the error logged ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Issue with data not refreshing when using router push in NextJS version 13

I have implemented a delete user button on my user page (route: /users/[username]) which triggers the delete user API's route. After making this call, I use router.push('/users') to navigate back to the users list page. However, I notice tha ...

What steps should I follow to include Sass compilation in my Angular CLI 6 project in the angular.json file?

I recently started working on a project in Angular using the latest version of Angular CLI 6.0. However, I need to enable Sass compilation for my existing project. Typically, you can specify this during project creation, but since mine is already set up wi ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

I'm having difficulty with the installation of the @angular/CLI package

npm ERROR 404: Package @angular/CLI@latest Not Found ** log: ** 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\&b ...

I encountered a frustrating issue of receiving a 400 Bad Request error while attempting to install

I am currently in the process of installing Angular CLI using npm to incorporate Angular 4 into several projects. Unfortunately, I keep encountering a 400 Bad Request error. Has anyone else faced this issue before and found a solution? I have already searc ...

Jest | Testing Tool for Functions with Multiple Parameters

I have developed a new tool that requires 3 parameters: value (string), service (any - an actual GET service), and name (string). Below is the code for the tool: import { serverErrorResponseUtil } from 'util/serverErrorResponseUtil'; import { H ...