Angular подписка становится неопределенной в локальной переменной - PullRequest
0 голосов
/ 30 января 2020

У меня есть локальная переменная, и я хочу использовать Observable в нашем Angular компоненте только для того, чтобы подписаться на него и хранить ответ локально, но кое-как, как он становится неопределенным всегда. Любые подсказки, почему его не назначают?

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();
    }

}

1 Ответ

2 голосов
/ 30 января 2020

Попробуй так,

subscription;

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

ngOnDestroy(): void {
  if (this.subscription) {
   this.subscription.unsubscribe();
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...