Skip to content Skip to sidebar Skip to footer

Service S Undefined Whenever I Try To Call A Method From It

I'm following Jogesh Muppala's Angular course on Coursera, and I'm stuck at the beginning of Week 4, where he's using HttpClient to communicate with the server. I've followed the i

Solution 1:

The problem is that you have defined a parameter in the constructor, but when you call new DishService() you don't pass this value in. In general, you can simplify your providers section and should be able to fix your problem in the same turn.

providers: [
    DishService,
    PromotionService,,
    ProcessHTTPMessageService,
    {provide: 'BaseURL', useValue: baseURL}
],

If you don't need any special construction for your provider, you can just pass in the class and the dependency injection framework will take care of the dependencies for you.

I don't see why you should use the older style of writing providers, but if you want to make it more complicated you need to use a factory, once you require dependencies. But as I see it there is no point in doing that in your case.

Solution 2:

I think you need to add @Injectable() decorator in your service class and also these after this code..

import {Dish} from'../shared/dish';
   import {DISHES } from'../shared/dishes';
   import {Observable, of} from'rxjs';
   import { delay } from'rxjs/operators';

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

   @Injectable({
     providedIn: 'root',
   })
   exportclassDishService {

  constructor(private http: HttpClient) {

   }

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

  }

}

No need to place this service in provider options of NgModule decorator of root module (like : app.module) due to the 'providedIn' flag and must need to add HttpClientModule in imports options of NgModule decorator also. Hope this helps.

Post a Comment for "Service S Undefined Whenever I Try To Call A Method From It"