主题订阅在角度8中不起作用。似乎主题无法发出事件

时间:2020-05-03 12:15:08

标签: angular typescript rxjs angular8

我正在尝试在获取数据时发出一个主题,但是该主题没有发出任何事件

即使在组件的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);
        }
      );
}

1 个答案:

答案 0 :(得分:2)

您将一无所获,因为在您的组件ngOnInit中进行预订后没有释放任何值。如果要将当前值发送给新订阅者,请使用BehaviorSubject而不是Subjecthttps://rxjs-dev.firebaseapp.com/api/index/class/BehaviorSubject