Fearcoder
Fearcoder

Reputation: 788

Data binding results in [object Object]

I am trying to bind the records of rows to my view. This is my code on the backend:

 [Route("GetCarCount")]
        [HttpGet]
        public async Task<long> Count()
        {
            return await _context.Cars.CountAsync();
        }

I have test this and it works. I get a result like a number

9

Now I want to bind this on the view this is my code in the service.

 getCount() {
    return this.http.get(this.baseUrl + 'GetCarCount');
  }

And I call this method like this:

 GetCarCount() {
    this.countrecords = this.carservice.getCount();
  }

I have declared a variable like this:

countrecords: any;

Now I bind it like this:

<label>Records count: = {{countrecords}}</label>

It doesn't show the number 9instead I get [object Object]

I have tried like this but it didn't work for me

JSON.parse JSON.stringify

What am I doing wrong?

Upvotes: 0

Views: 569

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39432

Judging from your implementation, countrecords will be of type Observable<number>. Use the async pipe in your template to unwrap its value.

<label>Records count: = {{countrecords | async}}</label>

Upvotes: 3

ishan srivastava
ishan srivastava

Reputation: 383

The countrecords varibales will be a observable. The http methods like .get or .put are Cold Observables ->

Cold observables start running only upon subscription, i.e., the observable sequence only starts pushing values to the observers when Subscribe is called. (…) This is different from hot observables such as mouse move events or stock tickers which are already producing values even before a subscription is active.

Hence

  • It's highly probably that the API request is not being made
  • Moreover in the {{countrecords}} it won't show the value that was returned to you since that holds a subscription (and not the value you'll get on subscribing that subscription)

What I would suggest is

GetCarCount() {
this.carservice.getCount().subscribe((value)=>{this.countrecords=value});
}

and the rest will remain the same. Hope it helps.

Upvotes: 2

Related Questions