Reputation: 31
I'm trying to get data from a local server, but nothing is coming up. The idea is that it is retrieved by a service, which passes back an observable, and any components that need the data subscribes to the observable.
dish.service.ts
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'
})
export class DishService {
constructor(private http: HttpClient) {
}
getDishes(): Observable<Dish[]>{
console.log("Hey");
return this.http.get<Dish[]>(baseURL + 'dishes');
}
}
menu.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { Dish } from '../shared/dish';
import {DishService} from '../services/dish.service';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
dishes: Dish[];
constructor(private dishService: DishService, @Inject('BaseURL') private BaseURL) { }
ngOnInit() {
(dishService => dishService.getDishes().subscribe(dishes => this.dishes = dishes))
}
}
It passes the data to menu.component.html, which worked fine before the addition of the server, so I know it isn't that. Here's what's interesting: the console.log("Hey") in the first code sample doesn't execute. It's as if the dishSerivce.getDishes() method isn't even being called by the MenuComponent. I don't know how to dig any deeper than that. Does anyone have any other ideas?
Upvotes: 0
Views: 382
Reputation: 346
The problem is in line
(dishService => dishService.getDishes().subscribe(dishes => this.dishes = dishes))
Basically you declare a function here, without calling it. Your code is equivalent to
ngOnInit(){
function(dishService){
return dishService.getDishes().subscribe(dishes => this.dishes = dishes);
}
}
Consider the following code which actually calls the function, passing this.dishService
as an argument.
(dishService => dishService.getDishes().subscribe(dishes => this.dishes = dishes))(this.dishService)
Having said that, the correct approach would be
ngOnInit() {
this.dishService.getDishes()
.subscribe(dishes => this.dishes = dishes);
}
Upvotes: 1
Reputation: 222722
It should be as follows,
ngOnInit() {
dishService.getDishes().subscribe(dishes => this.dishes = dishes))
}
Upvotes: 0