为RxJS的subscribe()内的组件变量赋值

时间:2017-06-12 19:35:14

标签: angular rxjs observable

我正在尝试订阅可观察源,以便将源的值绑定到组件变量(event: Event)。

尽管传递给subscribe()函数的观察者函数正确执行,并且observable到达预期值,但组件变量event: Event始终未定义。

为什么会发生这种情况?如何解决这个问题?

@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'
    }

1 个答案:

答案 0 :(得分:0)

这里只有解释是订阅中的event没有正常下来。如果您尝试在订阅块中打印它,您将看到event未定义

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

然后您必须修复EventBus服务