我的主题在Angular中无法正常工作 [英] My Subject is not working properly in Angular

查看:37
本文介绍了我的主题在Angular中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我照常在服务文件中创建了一个主题

I've created a subject in service file as usual

editLectures = new Subject<Lecture>();

getEditLectureListener() {
  return this.editLectures.asObservable();
}

我正在从一个组件发送数据(我在 console.log 上获取正确的数据)

From one component I'm sending a data (I am getting proper data when I console.log it)

onUpdate(lec: any) {
  this.attendanceService.emitLecture(lec);
}

在另一个组件上,我正在听主题:

On another component I'm listening to the Subject:

this.updateLecture = this.attendanceService.getEditLectureListener().subscribe(result => {
  // my code
  // on console.log(result) i am not getting anything and other listeners
  // are working perfectly, the only difference is that
  // its not emitting data from http response 
});

在使用中,我正在发射数据:

In service I'm emitting the data:

emitLecture(lec: Lecture) {
  this.editLectures.next(lec);
  this.router.navigate(['edit-lecture']);
}

推荐答案

您需要使用BehaviorSubject而不是Subject,这样最后发出的值将可用于新订阅者(实例化您的侦听器组件时).

You need to use BehaviorSubject instead of Subject so the last emitted value will be available for new subscriber (when your listener component is instantiated).

editLectures = new BehaviorSubject<Lecture>(null);

这篇关于我的主题在Angular中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆