0

I have a local variable and want to use the Observable in our Angular Component just to subscribe to it and store the response locally,but some how its getting undefined always.Any clues why its not assigning?

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

}
MonkeyScript
  • 4,776
  • 1
  • 11
  • 28
Avinash.Byalihal
  • 137
  • 2
  • 7
  • 22
  • Please make stackblitz – Aarsh Jan 30 '20 at 04:30
  • That's how observable works and it should print undefined. I believe you are making an HTTP call in your service to fetch data. Once you start your subscription, it will run asynchronously with the parent function i.e. the code below works without waiting for the subscription to complete. – MonkeyScript Jan 30 '20 at 04:32

1 Answers1

2

Try so,

subscription;

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

ngOnDestroy(): void {
  if (this.subscription) {
   this.subscription.unsubscribe();
  }
}
qwerty
  • 679
  • 5
  • 12