0

我有一个局部变量,想在我们的 Angular 组件中使用 Observable 只是为了订阅它并在本地存储响应,但是它总是如何变得未定义。任何线索为什么它不分配?

export class ScheduleHistoryComponent implements OnInit, OnDestroy {

    subscription: Subscription = new Subscription();
    toAccountListDto: any;

    constructor(public paymentService: PaymentService) {}

    ngOnInit(): void {
        this.subscription.add(this.paymentService.getLiteAccountsList()
            .subscribe((res: any) => {
                this.toAccountListDto = (res.data.accountDtoList);
                this.toAccountListDto = this.toAccountListDto.filter(account => account.accountSource.toUpperCase() === 'DDA' ||
                    account.accountSource.toUpperCase() === 'SVG');
                console.log('Inside', this.toAccountListDto); < -- --its prints output here
            }, error => {
                console.error();
            })
        );
        console.log('Outside', this.toAccountListDto); < -- --its prints output as undefined
    }

    ngOnDestroy(): void {
        this.subscription.unsubscribe();
    }

}
4

1 回答 1

2

试试看,

subscription;

ngOnInit(): void {
    this.subscription = this.paymentService.getLiteAccountsList().subscribe(...);
}

ngOnDestroy(): void {
  if (this.subscription) {
   this.subscription.unsubscribe();
  }
}
于 2020-01-30T04:29:14.200 回答