I'm trying to fetch data from firebase, but facing an error
"Property 'subscribe' does not exist on type 'OperatorFunction'"
any idea? whats missing here?
import { Injectable } from '@angular/core';
import {HttpClient, HttpResponse} from '@angular/common/http';
import {Response} from '@angular/http';
import {RecipeService} from '../recipes/recipe.service';
import {Recipe} from '../recipes/recipe.model';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataStorageService {
constructor(private httpClient: HttpClient,
private recipeService: RecipeService) {}
storeRecipes() {
return this.httpClient.put('https://ng-recipe-10b53.firebaseio.com/recipes.json',
this.recipeService.getRecipes());
}
getRecipes() {
this.httpClient.get('https://ng-recipe-book.firebaseio.com/recipes.json');
map(
(response: Response) => {
const recipes: Recipe[] = response.json();
for (const recipe of recipes) {
if (!recipe['ingredients']) {
recipe['ingredients'] = [];
}
}
return recipes;
}
)
.subscribe(
(recipes: Recipe[]) => {
this.recipeService.setRecipes(recipes);
}
);
}
}
One thing that got me, there is a static and a pipeable version of many functions.
For example, combineLatest(a$, b$).subscribe() will give you a similar error about OperatorFunction<T,R> (T and R will vary based on your observables) if you import it from rxjs/operators! Import it from rxjs and no problemo.
If you're playing around with something, your IDE might very well auto-import from rxjs/operators, and not change it when you try and use it outside a pipe.
You are calling subscribe on your HTTP call in the getRecipes method. The return value of subscribe is of type Subscription, not Observable. Thus, you cannot use that value in your storeRecipes method, because a Subscription cannot be observed; only an Observable can.
Moreover, your getRecipes logic is bad. You use map after your HTTP call in getRecipes, however there is a semicolon before it. Did you even execute this code? It is not valid TypeScript/Angular/RxJS and will not compile.
You can either chain your operators properly (using the old RxJS syntax), or use pipeable operators as in my example below (the new RxJS syntax).
Change your getRecipes function to this and it should work:
getRecipes() {
this.httpClient
.get('https://ng-recipe-book.firebaseio.com/recipes.json')
.pipe(
map((response: Response) => {
const recipes: Recipe[] = response.json();
for (const recipe of recipes) {
if (!recipe['ingredients']) {
recipe['ingredients'] = [];
}
}
return recipes;
}),
tap((recipes: Recipe[]) => {
this.recipeService.setRecipes(recipes);
})
);
}
And make sure to import map and tap from rxjs/operators:
import { map, tap } from 'rxjs/operators';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With