-1

I am learning Angular and have the following question regarding async functions. Please check the code below:

This is the receiveInfo( ) method inside of my transferService

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { CountryAllData } from 'src/app/Interfaces/CountryAllData';

export class TransferService {
  private apiResponse = new BehaviorSubject<CountryAllData[]>({} as CountryAllData[]);
  
  constructor() {}

  receiveInfo() {
    return this.apiResponse.asObservable();
  }
}

I import the transferService inside of Chart Component and define the getApiResponse ( ) method:

import { Component, OnInit } from '@angular/core';
import { TransferService } from 'src/app/Services/Transfer/transfer.service';
import { CountryAllData } from 'src/app/Interfaces/CountryAllData';


export class ChartComponent implements OnInit, AfterViewInit {

constructor(private transferService: TransferService) {}

  getApiResponse(after: Function) {
    this.transferService.receiveInfo().subscribe((d) => this.setApiResponse(d, after));
  }

I would like to call the after () function after setting the apiResponse using this.setApiResponse So far I am doing it by passing the after () function as a call back to the setApiResponse.

How could I do it using promises ?

Thank you

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36
Elie
  • 1
  • instead of converting it to promise, you can use take functionality. It'll automatically unsubscribe after n takes. ).pipe(take(1)).subscribe( res => ...). This acts as a promise – Pratik Agarwal Nov 09 '22 at 08:09

1 Answers1

0

You can do .toPromise() on the observable response from getApiResponse and await it and call it afterwards

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36
  • Thanks for your answer. I just saw that .toPromise( ) has been deprecated. I guess we need to use firstValueFrom( ) – Elie Sep 25 '21 at 16:55