数据绑定产生[对象Object]

时间:2019-06-19 14:15:47

标签: html .net angular typescript .net-core

我正在尝试将行记录绑定到我的视图。这是我在后端的代码:

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

我已经对此进行了测试,并且可以正常工作。我得到类似数字的结果

9

现在,我想将此绑定到视图中,这是我在服务中的代码。

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

我这样调用此方法:

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

我已经声明了这样的变量:

countrecords: any;

现在,我将其绑定为这样:

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

它没有显示数字9,而是显示[object Object]

我已经尝试过了,但是对我没用

JSON.parse JSON.stringify

我在做什么错了?

2 个答案:

答案 0 :(得分:3)

从您的实现来看,countrecords的类型为Observable<number>。使用模板中的async管道解开其值。

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

答案 1 :(得分:2)

countrecords 自变量将是可观察到的。 像.get或.put这样的http方法都是Cold Observables->

  

冷的可观察对象仅在订阅时开始运行,即,可观察的序列仅在以下情况下开始将值推入观察者   订阅被调用。 (…)这与诸如   作为已经产生的鼠标移动事件或股票报价器   值,即使订阅处于活动状态也是如此。

因此

  • 很有可能没有发出API请求
  • 此外,在{{countrecords}}中,它不会显示由于持有订阅而返回给您的值(而不是您订阅该订阅时得到的值)

我建议的是

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

,其余的保持不变。 希望对您有所帮助。