Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[baseURL]

10.9k Views Asked by At

please help .. I'm stuck here with angular HTTP
I'm trying to fetch JSON data and pictures from JSON-server
using cmd at json-server I run (json-server --watch db.json) ... then ==>

My server structure

json-server 
    |
    |__ public (folder for assets)
    |      |__ images (folder for images)
    |
    |__ db.json (json database)

I have the following error !!?

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[baseURL -> baseURL -> baseURL]: 
  NullInjectorError: No provider for baseURL!
get@http://localhost:4200/vendor.js:46512:27

... etc

dish.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { baseURL } from '../shared/baseurl';
import { map } from 'rxjs/operators';
import { Dish } from '../shared/dish';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class DishService {
  constructor(private http: HttpClient) { }

  getDishes(): Observable<Dish[]> {
    return this.http.get<Dish[]>(baseURL + 'dishes');
  }

}

dish.ts (just class to get data from json server)

import { Comment } from './comment';

export class Dish {
    id: string;
    name: string;
    image: string;
    category: string;
    featured: boolean;
    label: string;
    price: string;
    description: string;
    comments: Comment[];
}

shared folder > baseurl.ts

export const baseURL = 'http://localhost:3000/';  // json server URL

menu.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
...
export class MenuComponent implements OnInit {
  dishes: Dish[];

  constructor(private dishService: DishService,
    @Inject('baseURL') private baseURL: string) { }

  ngOnInit() {
    this.dishService.getDishes().subscribe(dishes => this.dishes = dishes);
  }

menu.component.html

  <div fxFlex *ngIf="dishes">
    <mat-grid-list cols="2" rowHeight="200px">
      <mat-grid-tile *ngFor="let dish of dishes" [routerLink]="['/dishdetail', dish.id]">
        <img height="200px" src="{{ baseURL + dish.image }}" alt={{dish.name}}>
        <mat-grid-tile-footer>
          <h1>{{dish.name | uppercase}}</h1>
        </mat-grid-tile-footer>
      </mat-grid-tile>
    </mat-grid-list>
  </div>

app.module.ts

import { HttpClientModule } from '@angular/common/http';
import { baseURL } from './shared/baseurl';
...
imports { HttpClientModule },
providers: [
  DishService,
  {provide: 'BaseURL', useValue: baseURL}
]
1

There are 1 best solutions below

0
On

I found a solution to my problem and it's very simple

in menu.component.ts

change this

@Inject('baseURL') private baseURL: string

into this

@Inject('BaseURL') public BaseURL