【问题标题】:Binding data to Html tags with data received from REST API | IONIC and Angular使用从 REST API 接收的数据将数据绑定到 Html 标签 |离子和角度
【发布时间】:2021-08-13 16:38:18
【问题描述】:

尝试使用 REST API 构建 woocommerce 应用

基本上,我使用 promise 将数据接收到变量中

我使用相同的变量将数据显示到前端 HTML

<h3 *ngIf = "onsale" style="text-align:center;font-weight: 800;margin-top:5px">Rs. {{productregprice}} / {{productonsaleprice}}</h3>
        <h3 *ngIf = "!onsale" style="text-align:center;font-weight: 800;margin-top:5px">Rs. {{productonsaleprice}}</h3>

我面临的问题是 - 随着休息 API 调用完成,数据被加载到变量 productregprice 和 productonsaleprice 中

同时在前端 - HTML 视图被渲染,因此它给出了未定义的错误

我无法理解如何等待异步调用完成然后将数据提供给 HTML 标签以显示实际价格而不是 0

我的打字稿代码是

productregprice = 0;
    productonsaleprice = 0;
    onsale = true;
    productshortdescription =   "";

catids = this.route.getCurrentNavigation().extras.state.productid;
    secondurl = `${this.url}/wp-json/wc/v3/products/${this.catids}?consumer_key=${this.key}&consumer_secret=${this.secretkey}`;

constructor(private http: HttpClient,private route: Router) 
   {
     console.log(this.route.getCurrentNavigation().extras.state.productid);
     this.product = this.getProductsData().then(res=>console.log(res));
     console.log(this.product);
     if(typeof this.product.images != 'undefined')
                    {   
                        this.productimages = this.product.images;
                    }
                    else
                    {

                        this.productimages = [];
                    }
                    console.log("loaded");
   }



getProductsData()
    {
            return new Promise(resolve => {this.http.get(this.secondurl).subscribe(productdata => {resolve(productdata);});});
    }

请帮忙

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    编辑:对那个 HTML 元素使用 *ngIf="product &amp;&amp; (other conditions)"。 这应该是评论,但由于声誉低,将其添加为答案。 您能否分享您使用this.productproductregpriceproductonsaleprice 赋值的代码。 您已初始化 productonsaleprice = 0,当您在分母中使用它时可能会引发错误。

    【讨论】:

    • 数据正在 this.product 的构造函数中加载,在前端我正在使用

      { {product.name}}

      但由于 product.name 在几秒钟后获取数据异步,我无法在屏幕上看到 h2
    • 只需将 *ngIf="product && (other conditions)" 添加到

      标记中。这应该工作

    • 不工作 - 尝试使用

      {{product.name}}

    • 如果你能在 stackblitz 上分享你的代码就太好了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 2019-03-30
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多