订阅中的组件变量未更新

时间:2019-02-24 07:14:15

标签: angular

在服务中使用EventEmitter进行跨组件通信。

当它发出事件时,它的调用订阅并在日志中打印预期的数据。但是,当尝试更新属性时,它没有这样做,也没有收到任何错误。

在调试中,当我检查this.selectedCategory订阅代码中的值时,我可以看到它的更新,但是当我看到selectedCategory = {} as ArtCategory;时,它显示

  

“无法读取未定义的属性'selectedCategory'”

该如何解决?

服务中的事件发射器

export class GalleryService {
  categorySelected = new EventEmitter<ArtCategory>();
  catagories : ArtCategory[] = [];
  constructor() { }
}

事件触发代码

export class GalleryComponent implements OnInit {
  artCategories: ArtCategory[];

  constructor(private artCategoryService: ArtCategoryService, private galleryService: GalleryService) {
  }

  ngOnInit() {
    this.artCategories = this.artCategoryService.categories;
  }

  showCategoryArts(artCategory: ArtCategory) {
    this.galleryService.categorySelected.emit(artCategory);
    this.router.navigate(['categoryArts']);
  }
}

事件订阅代码

export class CategoryArtsComponent implements OnInit {

  selectedCategory = {} as ArtCategory;
  constructor(private artService : ArtsService, private galleryService : GalleryService) { }

  ngOnInit() {
    this.galleryService.categorySelected.subscribe(
      (artCategory: ArtCategory) => {
          console.log(artCategory);
          this.selectedCategory = artCategory;
      });
  }
}

0 个答案:

没有答案