问题描述
我正在尝试从firebase
获取数据,但是遇到错误
I'm trying to fetch data from firebase
, but facing an error
有什么主意吗?这里缺少什么?
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);
}
);
}
}
推荐答案
您正在通过getRecipes
方法在HTTP调用中调用subscribe
. subscribe
的返回值是Subscription
类型,而不是Observable
类型.因此,您不能在storeRecipes
方法中使用该值,因为无法遵守Subscription
;只有Observable
可以.
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.
此外,您的getRecipes
逻辑不好.在getRecipes
中的HTTP调用之后,您可以使用map
,但是它前面有一个分号.您是否执行过此代码?它是无效的TypeScript/Angular/RxJS,将无法编译.
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.
您可以正确地链接您的运算符(使用旧的RxJS语法),也可以使用可管道运算符,如下例所示(新的RxJS语法).
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).
将您的getRecipes
函数更改为此,它应该可以工作:
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);
})
);
}
并确保从rxjs/operators
导入map
和tap
:
import { map, tap } from 'rxjs/operators';
这篇关于类型'OperatorFunction< Response,Recipe []>'上不存在属性'subscribe'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!