《仿盒马》app开发技术分享-- 扫一扫功能(35)


## 技术栈


Appgallery connect

## 开发准备

随着app的逐渐完善,我们现在需要在细节处做更多的打磨,在首页我们添加了很多静态的按钮和组件,现在我们开始对这些组件进行功能的添加,这次首先实现的是首页头部的扫一扫功能,扫一扫我们实现扫码后跳转商品详情页



## 功能分析

要实现扫一扫的功能,我们有两种选择,首先是zxing,然后是scankit,这里我们选择使用scankit,因为它针对多种复杂扫码场景做了识别优化,提升扫码成功率与用户体验,我们自己要处理的内容就会少很多,我们主要扫码内容就是商品的id,通过扫描商品id对应的二维码,携带id跳转到对应的商品详情页面,查询出对应的商品详情展示



## 代码实现

首先我们在二维码扫描的按钮添加事件回调


```c

 private  onSearchClick?: () => void

  Image($r('app.media.scan'))

        .width(24)

        .height(24)

        .margin({ left: 12 })

        .onClick(()=>{

          this.onSearchClick!()

        })


```

然后我们在引用组件的地方调用Scankit


```c

   CommonSearchBar({onSearchClick:()=>{

                      let options: scanBarcode.ScanOptions = {

                        scanTypes: [scanCore.ScanType.ALL],

                        enableMultiMode: true,

                        enableAlbum: true

                      };

                      try {

                        scanBarcode.startScanForResult(getContext(this), options).then((result: scanBarcode.ScanResult) => {

                          hilog.info(0x0001, '[Scan CPSample]', `Succeeded in getting ScanResult by promise with options, result is ${JSON.stringify(result)}`);

                          if (result.originalValue!=null) {

                            let product: ProductDetailModel = {

                              id: Number(result.originalValue)

                            };

                            router.pushUrl({

                              url: 'pages/component/ProductDetailsPage',

                              params: product

                            }, (err) => {

                              if (err) {

                                console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);

                                return;

                              }

                              console.info('Invoke pushUrl succeeded.');

                            });

                          }


                        }).catch((error: BusinessError) => {

                          hilog.error(0x0001, '[Scan CPSample]',

                            `Failed to get ScanResult by promise with options. Code:${error.code}, message: ${error.message}`);

                        });

                      } catch (error) {

                        hilog.error(0x0001, '[Scan CPSample]',

                          `Failed to start the scanning service. Code:${error.code}, message: ${error.message}`);

                      }

                  }})

```

在回调中我们获取了扫码的内容,把扫码内容传递到商品详情页


```c

//先新建一个传递参数的实体

export class ProductDetailModel {

  id: number = 0;

}


//商品详情页根据获取的id查询对应的商品

  let databaseZone = cloudDatabase.zone('default');

   let product = await router.getParams() as ProductDetailModel;

    console.info('Received params:',product);

    let condition1 = new cloudDatabase.DatabaseQuery(home_product_list);

    condition1.equalTo("id",product.id)

    let productDetail = await databaseZone.query(condition1);

    let json = JSON.stringify(productDetail)

    let list:HomeProductList[]= JSON.parse(json)

    this.productParams=list[0]

    hilog.error(0x0000, 'testTag', `Failed to query data, code: ${this.productParams}`);


```

到这里就实现了扫码进入商品详情的功能


请使用浏览器的分享功能分享到微信等