Search code examples
htmlangulartypescriptfrontendbackend

Injector Error: R3InjectorError(Standalone[_AppComponent])[_WebService -> _WebService -> _WebService]:


I'm a student so apologies for any incorrect termonology or my lack of understanding.

Im creating an Angular front-end to interact with my back end API. I am currently getting the following error in the console of the web page (inspect -> console). Injection Error Console:

As far as I know, my classes and files are set up perfectly fine. I will provide the relevent code below:

web.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class WebService {

  beer_list: any;

  constructor(private http: HttpClient) { }

  getBeers() {
    return this.http.get(
              'http://localhost:5000/api/v1.0/beers')
        .subscribe((response: any) => {
            this.beer_list = response;
            console.log(response);
        });
  }

}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { BeersComponent } from './beers.component';
import { WebService } from './web.service';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent, BeersComponent
  ],
  imports: [
    BrowserModule, HttpClientModule
  ],
  providers: [WebService],
  bootstrap: [AppComponent]
})
export class AppModule { }

beers.component.ts:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { WebService } from './web.service';


@Component({
  selector: 'beers',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './beers.component.html',
  styleUrls: ['./beers.component.css']
})


export class BeersComponent{

  beer_list: any;

  constructor(public webService: WebService) { }

  ngOnInit() {
    this.webService.getBeers();
  }

}

I have tried absolutely everything I can think of. I am also following a tutorial given by my tutor, and I have checked his code and compared it with mine, and I have everything exactly the same.


Solution

  • A description of what you have right now

    • component calls service
    • service calls http endpoint
    • http eventually returns a value, which is assigned to a local variable on the service
    • the variable on the component never gets the http contents

    Realizing that you are doing an exercise I'm being careful not to give you the answer directly. The above should point you in the right direction. Let me know if it needs more.