我正在尝试在获取数据时发出一个主题,但是该主题没有发出任何事件
即使在组件的ngOnInit()
中,我也没有在订阅代码中写入日志。
服务中的代码为
@Injectable()
export class RecipeService {
recipesChanged = new Subject<Recipe[]>();
setRecipes(recipe: Recipe[]){
console.log('setrecipes () is called');
this.recipes=recipe;
console.log('recipe list after set recipes ()-->'+recipe);
this.recipesChanged.next(this.recipes.slice());
}
现在在组件中
export class RecipeListComponent implements OnInit , OnDestroy {
recipes :Recipe []=[];
subscription : Subscription;
constructor(private recipeService : RecipeService ,
private router : Router ,private route : ActivatedRoute
) {}
ngOnInit() {
console.log('ngOnLINit is called of recipe-list')
this.subscription = this.recipeService.recipesChanged
.subscribe(
(recipes: Recipe[]) => {
this.recipes = recipes;
console.log('recipe-list recipes are :' + recipes);
}
);
}
答案 0 :(得分:2)
您将一无所获,因为在您的组件ngOnInit
中进行预订后没有释放任何值。如果要将当前值发送给新订阅者,请使用BehaviorSubject
而不是Subject
:https://rxjs-dev.firebaseapp.com/api/index/class/BehaviorSubject