0
內的組件變量賦值爲了將源的值綁定到組件變量(event: Event
),我嘗試訂閱可觀察源。爲RxJS的subscribe()
儘管傳遞給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'
}
您是說,如果你把一個'的console.log('的東西');''通過this.event = event',它會按預期的方式向控制檯輸出'something''。另外,'console.log(this.event); < - 這是'未定義'似乎很自然,因爲訂閱者功能剛剛建立,因此很可能尚未執行(這不會影響「ngIf」應該成爲最終在函數執行時爲true)。 – acdcjunior
添加到剛纔提到的@acdcjunior中 - 嘗試將
添加到您的模板中,並查看實際值是否從false更改爲true。 – Tamas