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.