我正在尝试从 firebase
获取数据,但遇到错误
任何想法?这里缺少什么?
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);
}
);
}
}
最佳答案
您正在 subscribe
方法中对 HTTP 调用调用 getRecipes
。 subscribe
的返回值是 Subscription
类型,而不是 Observable
。因此,您不能在 storeRecipes
方法中使用该值,因为无法观察到 Subscription
;只有 Observable
可以。
此外,您的getRecipes
逻辑是错误的。您在 map
中的 HTTP 调用之后使用 getRecipes
,但是它前面有一个分号。你甚至执行过这段代码吗?它不是有效的 TypeScript/Angular/RxJS 并且不会编译。
你可以正确地链接你的操作符(使用旧的 RxJS 语法),或者使用 pipeable operators 就像我下面的例子一样(新的 RxJS 语法)。
将您的getRecipes
函数更改为此,它应该可以工作:
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);
})
);
}
并确保从
map
导入 ojit_code 和 tap
:import { map, tap } from 'rxjs/operators';