Тема подписки не работает в angular 8 .. Кажется, субъект не может отправлять события - PullRequest
0 голосов
/ 03 мая 2020

Я пытаюсь выдать субъект при получении данных, но субъект не генерирует никаких событий

Даже в компоненте 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 Ответ

2 голосов
/ 03 мая 2020

Вы ничего не получите, потому что после подписки в ngOnInit вашего компонента нет значения. Если вы хотите передать текущее значение новым подписчикам, используйте BehaviorSubject вместо Subject: https://rxjs-dev.firebaseapp.com/api/index/class/BehaviorSubject

...