0

我在 Angular上遇到了主题问题。

在我的服务中,我有formSendStatus = new Subject<boolean>();

我有一个form.component将为该主题设置下一个值,如下所示myservice.formSendStatus.next(true)

然后,我有另一个订阅它的组件:

ngOnInit() {
   myservice.formSendStatus.subscribe(
      data => console.log(data)
   );
}

我在控制台上什么也没有。难道我做错了什么?

4

2 回答 2

1

你的问题是你不应该订阅formSendStatus而不是你应该订阅这样一个可观察的属性formSendStatus

export class MyService {
   formSendStatus: Subject<boolean>;
   formSend$: Observable<boolean>;
   constructor() {
     this.formSendStatus = new Subject<boolean>();
     this.formSend$ = this.formSendStatus.asObservable();
   }
}

然后在你的组件中你应该这样做:

ngOnInit() {
   myservice.formSend$.subscribe(
      data => console.log(data)
   );
}

现在每次你next()formSendStatus组件中发出一个值都会被 observable 知道formSend$

于 2019-11-28T15:10:29.837 回答
0

使用主题时,您必须对其调用 next() 以使其发出值。对于普通主题(您在此处使用),您需要确保在调用 next 时您已经订阅。如果那不可能,您可以使用 BehaviorSubject 或 ReplaySubject,因为它们会缓存值并将它们发送给新订阅者。

formSendStatus = new ReplaySubject<boolean>(1) // the number is the number of values to cache, 1 means only store and emit the last value, no number means store and cache all values

formSendStatus = new BehaviorSubject<boolean>(false); // behavior subjects require a default value, in this case false is the default value
于 2019-11-28T15:16:05.757 回答