简体   繁体   English

为RxJS的subscription()中的组件变量分配一个值

[英]Assign a value to a component variable inside RxJS's subscribe()

I'm trying to subscribe to an observable source in order to bind the source's value to a component variable ( event: Event ). 我试图订阅一个可观察的源,以便将源的值绑定到组件变量( event: Event )。

In spite of the fact that the observer function passed to the subscribe() function executes correctly, and the observable arrives at expected, the component variable event: Event is always undefined. 尽管传递给subscribe()函数的观察者函数可以正确执行,而可观察对象可以达到预期值,但组件变量event: Event始终是未定义的。

Why is that happening and how can I solve this problem? 为什么会发生这种情况,我该如何解决这个问题?

@Component({
    selector: 'event-detail',
    template: `
        <div *ngIf="event"> <-- this will never evaluate to 'true'
            ...
        </div>
    `,
})
export class EventCenterDetailComponent implements OnInit {
    event: Event;
    subscription: Subscription;

    constructor(
        private eventBus: EventBus
    ) {}

    ngOnInit() {
        this.subscription = this.eventBus.event$.subscribe((event: Event) => {
            this.event = event; <-- this assignment seems to have no effect on the component variable
        });
        console.log(this.event); <-- this is 'undefined'
    }

Only explanation here is that event in the subscribe is not coming down properly. 这里唯一的解释是订阅中的event没有正常下降。 You will see that event is undefined if you try to print it in the subscribe block 如果尝试在订阅块中打印该event则会看到该event未定义

...subscribe((event: Event) => {
   console.log(event); // this will print undefined most likely
});

Then you have to fix your EventBus service 然后,您必须修复EventBus服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM