我试图在从另一个服务获取数据时发出主题,但主题没有将值从 setRecipe() 传递到 getRecipe() 并且在组件的 ngOninit 中没有从服务中获取值。
@Injectable()
export class RecipeService{
recipesChanged = new Subject<Recipe[]>();
private recipes:Recipe[]=[];
constructor(private slService:ShoppingListService){}
setRecipes(recipe: Recipe[]){
this.recipesChanged.next(this.recipes.slice());
console.log("value from setRecipe()", this.recipes);
}
getRecipes(){
console.log("value from getRecipes()", this.recipes.slice());
return this.recipes.slice();
}
在配方列表组件中
export class RecipeListComponent implements OnInit, OnDestroy {
recipes:Recipe[];
subscription: Subscription;
constructor(private recipeService : RecipeService ,
private router : Router ,private route : ActivatedRoute
) {}
ngOnInit() {
this.recipeService.recipesChanged
.subscribe(
(recipes: Recipe[]) => {
console.log("recipes from recipe list comp",recipes);
this.recipes = recipes;
}
);
console.log("my recipes",this.recipes);
this.recipes= this.recipeService.getRecipes();
}
并且数据是从数据存储服务中的 firebase 获取的,并设置为配方服务的 setRecipe()。我从 Firebase 获取食谱的价值到数据存储服务,并且在 setRecipe() 日志中我得到了价值,但它没有设置我的食谱 [] 的值,因此它没有将值传递给组件。