0

I want to return amount to the given function.

I have make a function

    getWalletTotalAmont()
  {
    let amount= 0 ;

    this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal`,{user_id:2}).pipe(map(data => 
      {
        return  JSON.stringify(data);
      }),

    ).subscribe((data) =>
    {  

      let data_obj = JSON.parse(data);
      amount= data_obj.total_wallet_amount; 
      console.log(amount);   // it is printing 2500
    },

    );
    return amount;   // it is returning 0

  }
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46

1 Answers1

3

When using observables you don't return the actual value, but an observable. The observable is a stream where you subscribe to listen for events. The event is actually the http response. Normally handling http request in angular is done like this:

getWalletTotalAmont(): Observable<any>{
  return this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal`,{user_id:2})
}

No need to call json.parse angular does that automatically.

And you can use this function in different ways in your component:

@Component(...)
export class MyComponent  {
   amount;

   constructor(private walletService: WalletService) {}

   loadWalletAmount() {
    this.walletService.getWalletAmount().subscribe(amount=> {this.amount = amount});
   }
  }

You trigger a function in your component which calls the service and write the result to a local variable in this case amount. Afterwards this variable can be used in your component to display the result.

An alternative is to use angulars async pipe:

  @Component(...)
    export class MyComponent implements OnInit  {
       amount$: Observable<any>;

       constructor(private walletService: WalletService) {}

       ngOnInit() {
        this.amount$ = this.walletService.getWalletAmount();
       }
      }

And in your template:

<div *ngIf="amount$ | async as amount>
  My amount is {{amount}}
</div>

EDIT:

If you want to show the amount on multiple views you have to provide a public variable of the service.

For example:

     @Injectable()
        export class WalletService {

          // I don't know what amount is, it would be better to provide a non null value here      
          amount: BehaviorSubject<any> = new BehaviorSubject(null);
          get amount$(): Observable<any> {
            return this.amount.asObservable();
          }

          constructor(private httpClient: HttpClient) {
            this.getWallet();
          }

          getWallet() {
            this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal`,{user_id:2})
            .subscribe(amount => this.amount=amount)
          }
        }

Then you can access the amount$ from anywhere:

 @Component(...)
    export class MyComponent implements OnInit  {
       amount: any;

       constructor(private walletService: WalletService) {}

       ngOnInit() {
        this.walletService.amount$.subscribe(amount => this.amount = amount);
       }
      }

BehaviorSubject saves the last emitted value and every new subscriber gets immediately this value.

J. S.
  • 2,268
  • 1
  • 12
  • 27
  • But I want to return amount in the given function,as I want do display wallet amount lots of places. – Ashish Kumar Sep 02 '19 at 07:58
  • See my edit. You have to expose a shared observable `get amount$(): Observable { return this.amount.asObservable(); }` in the service which then any component can access. – J. S. Sep 02 '19 at 08:45
  • @ J.S. Can you help a bit more? – Ashish Kumar Sep 02 '19 at 10:15
  • @ J.s Wallet amount is not working on fine page refresh, however it is working on again click... – Ashish Kumar Sep 02 '19 at 11:19
  • It depends on when valletService.getWallet() gets called. This function updates the value in BehaviorSubject. In my example it is called in the constructor of WalletService, but you can call it from everywhere. The best thing would be if you call it inside of `ngOnInit` of your component. – J. S. Sep 02 '19 at 11:25