如何使用Nativescript从Web服务直接搜索数据

问题描述 投票:0回答:2

我有这样的JSON响应:

{
    "StatusCode": 0,
    "StatusMessage": "OK",
    "StatusDescription": [
        {
            "product_id": "1",
            "Name": "ALMACINE",
            "qty": 5,
            "price": 10
        },.....
        {
            "product_id": "10",
            "Name": "BUPRENORFIN",
            "qty": 5,
            "price": 10
        },
        {
            "product_id": "11",
            "Name": "MAMIGUMMY",
            "qty": 5,
            "price": 10
        },
        {
            "product_id": "12",
            "Name": "CEFALEXINE",
            "qty": 5,
            "price": 10
        },
        {
            "product_id": "13",
            "Name": "BUPRENORFIN",
            "qty": 5,
            "price": 10
        },
        {
            "product_id": "14",
            "Name": "MAMIGUMMY",
            "qty": 5,
            "price": 10
        }
    ]
}

我想通过2个步骤在此JSON中搜索具有名称的产品。首先,我只想在此JSON中搜索。如果不存在任何产品,我想调用一个函数,以该名称响应所有产品。

我的代码:

  filteredMedic : Products[];

public SearchProducts(args) {
    let searchBar = <SearchBar>args.object;
    let searchValue = searchBar.text.toLowerCase();
    this.filteredMedic = searchValue.length ? this.products.filter(item => {
        return item['Name'].toLowerCase().includes(searchValue)
    }) : this.products;
    if(this.filteredMedic === []){
           this.productsservice.search_AllProduct(searchValue).subscribe(
            farmaciadata => {
                console.log('farmaciadata', farmaciadata)
          }
           );
    }
}

在此代码中,列表搜索很好,但是当this.filteredMedic为空时,步骤2不起作用。如何在后端搜索产品并在视图中显示?我的HTML代码:

<StackLayout *ngFor="let prod of filteredMedic; let i = index;">
............
</StackLayout>
angular search nativescript
2个回答
0
投票

尝试检查数组是否为空:

if (this.filteredMedic && this.filteredMedic.length == 0){
    this.productsservice.search_AllProduct(searchValue).subscribe(
        farmaciadata => {
            console.log('farmaciadata', farmaciadata)
    }
}

0
投票

[this.filteredMedic === []将始终返回false,因为[] === []在javascript中返回false。

相反,您需要检查this.filteredMedic.length === 0

© www.soinside.com 2019 - 2024. All rights reserved.