Book
Submodule 22.1: Angular and Reactive programming - Practice
Submodule 22.1: Angular and Reactive programming - Practice
Completion requirements
View
Updating the Services
Open dish.service.ts
and update its methods as follows:
...
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/delay';
import 'rxjs/add/observable/of';
...
@Injectable()
export class DishService {
constructor() { }
getDishes(): Observable<Dish[]> {
return Observable.of(DISHES).delay(2000);
}
getDish(id: number): Observable<Dish> {
return Observable.of(DISHES.filter((dish) => (dish.id === id))[0]).delay(2000);
}
}
Note
- The import of
{ Observable } from 'rxjs/Observable';
- The import of a couple of operators that we need in our dish service. We use these operators just to check that the Observables work.
import 'rxjs/add/operator/delay'
import 'rxjs/add/observable/of'
-
- If you want to emit only one value from your Observable, you will use the
of
method and this will take in whatever value that you want to emit in there. - The
delay(2000)
we want to delay the emitting of the value by two seconds
- If you want to emit only one value from your Observable, you will use the
- Also, while testing if observables work you should keep in mind the things below:
- The
Observable<Dish[]>
in the getDishes method. It returns an Observeble of Dish array instead of the Dish array itself. We will now update our service to return Observables, and we will update the components to make use of Observables. The reason is that when we update our services to use the HTTP service to go to a server to fetch the data, then in Angular, the HTTP methods will return Observables. Also, the services can simply pass the Observables to our components and let the components subscribe to these Observables and make use of the data that they obtained. - The
return Observable.of(DISHES)
to return those Dishes.