【发布时间】:2018-08-03 02:57:35
【问题描述】:
我正在尝试在 Angular 6 中的两个组件之间与 Subject 共享数据。 不知何故,它不起作用,我不知道为什么。我需要通过点击将数据从 compare.component 传递到 profile.component。当我点击时,数据没有传递。但是不知何故,当我返回然后再次单击时,它可以工作。 我做错了什么?
数据服务
import {Subject} from 'rxjs';
export class DataService {
data = new Subject();
}
profile.component
export class ProfileComponent implements OnInit {
constructor(private dataService: DataService, private router: Router) { }
ngOnInit() {
}
sendData(x) {
this.dataService.data.next(x);
this.router.navigate(['compare']);
}
}
比较组件
export class CompareComponent implements OnInit {
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.data.subscribe(
(data) => {
console.log(data);
}
);
}
}
【问题讨论】:
-
你在哪里调用 sendData()?
-
我猜 ProfileComponent 和 CompareComponent 没有相同的服务实例。其他人提到使用 BehaviorSubject。如果您有多个此主题的订阅者,这将是必要的,但在您的代码示例中,情况并非如此。如果您确实有多个订阅者,它确实应该是一个 BehaviorSubject。
标签: angular rxjs observable