【问题标题】:Value of count rows variable give me undefined although I assign it?计数行变量的值给我 undefined 虽然我分配了它?
【发布时间】:2021-09-20 20:07:41
【问题描述】:

我在 Angular 7 上工作,我面临问题计数行变量给我未定义的值

虽然返回的数据是 3

我需要的预期结果是 Count rows must equal 3

public Countrows:Number;
ngOnInit(): void {
countitems()
console.log("final count rows is" + this.Countrows);

}
countitems()
 {
  this._inventory.GetcountItems().subscribe(
    data =>this.Countrows=data[0].countItems 

  )
 }

虽然返回的数据值为 3,但它给了我最终数据未定义

count items 函数返回的数据

[
    {
        "countItems": 3
    }
]

我尝试过的:

console.log("final data" + data[0].countItems)
give me on console as 
final data 3

【问题讨论】:

    标签: angular typescript angular-material angular7 angular-components


    【解决方案1】:

    该值仅在回调上设置,而不是您console.log它的位置

     this._inventory.GetcountItems().subscribe(data => {
       console.log("final data" + data[0].countItems); // will work
       this.Countrows = data[0].countItems;
     });
    

    伪代码

    component.html

    <p>{{ countRowsDisplay }}</p>
    

    component.ts

    public countRows = 0;
    public countRowsDisplay = '';
    ngOnInit(): void {
      this.getCountItems();
      // below line won't work. called before subscription
      // this.displayCountItems();
    }
    
    getCountItems() {
      this._inventory.GetcountItems().subscribe(data => {
        this.countRows = data[0].countItems;
        this.displayCountItems(); //works
      });
    }
    
    displayCountItems() {
      this.countRowsDisplay = `Rows returned: ${ this.countRows }`;
    }
    

    【讨论】:

    • 虽然我通常按照上面发布的那样做
    • 如果GetCountItems() 返回您提到的数据,应该在订阅事件中工作。这会让你对 observables 有一个很好的了解。 rxjs.dev/guide/observable
    • 当为 data[0].countItems 制作控制台 .log 时,它给了我 3 但 this.Coutrows 给了我 undefined 你能帮帮我吗
    • 我得到的值在订阅内是好的,但在外下标不起作用 this._inventory.GetcountItems().subscribe(data => { this.Countrows = data[0].countItems; console.log("最终计数行里面是" + this.Countrows); // work give me 3 }); console.log("outside final count rows is" + this.Countrows);// 不起作用,给我未定义
    • 在您订阅之前该值将为空,因此如果您使用使用变量this.CountRows 的函数,您必须在分配值后在订阅回调中调用它 this.Countrows = data[0].countItems;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2018-07-13
    • 2016-02-14
    • 1970-01-01
    • 2015-12-24
    • 2020-06-02
    相关资源
    最近更新 更多