【问题标题】:Show each item of Array in a ListView在 ListView 中显示 Array 的每一项
【发布时间】:2019-04-11 09:20:12
【问题描述】:

我有一个带有 Angular 的 NativeScript 应用程序,我可以在其中扫描一些 BLE 设备。

虽然我能够提醒我在doStartScanning() 中找到的每个设备,但我无法在 ListView 中显示它们(我是 Angular 开发的新手)。

谁能告诉我怎么了?

我的 home-page.component.html 文件:

<StackLayout>
  <Label text="Bluetooth Connection!!!"></Label>
  <Button text="Scan QR code" (tap)="scanCode()" class="button button-positive"></Button>
  <Button text="Check Bluetooth" (tap)="doIsBluetoothEnabled()" class="button button-positive"></Button>
  <Button text="Enable Bluetooth" (tap)="doEnableBluetooth()" class="button button-positive"></Button>
  <Button text="Scan devices" (tap)="doStartScanning()" class="button button-neutral"></Button>
  <Button text="Stop Scanning" (tap)="doStopScanning()" class="button button-danger"></Button>

  <GridLayout rows="*">
    <ListView [items]="observablePeripheralArray" separatorColor="#90c3d4">
      <ng-template let-peripheral="item" let-i="index" let-odd="odd" let-even="even">
        <StackLayout orientation="horizontal" class="padded-label">
          <StackLayout class="padded-label-stack">
            <Label [text]="peripheral.name" class="title-label" textWrap="true"></Label>
            <Label [text]="peripheral.UUID" class="uuid-label" textWrap="true"></Label>
          </StackLayout>
        </StackLayout>
      </ng-template>
    </ListView>
  </GridLayout>

  <GridLayout>
    <ScrollView class="page">
      <StackLayout class="home-panel">
        <GridLayout rows="*">
          <ListView [items]="peripheralsArray">
            <ng-template let-peripheral="item" let-i="index" let-odd="odd" let-even="even">
              <StackLayout orientation="horizontal" class="list-group-item">
                <Label [text]="peripheral.name"></Label>
                <Label [text]="peripheral.UUID"></Label>
              </StackLayout>
            </ng-template>
          </ListView>
        </GridLayout>
      </StackLayout>
    </ScrollView>
  </GridLayout>
</StackLayout>

我的 home-page.component.ts 文件:

import { Component, OnInit } from "@angular/core";

var dialogs = require("tns-core-modules/ui/dialogs");
var bluetooth = require("nativescript-bluetooth");
var observable = require("tns-core-modules/data/observable");
var observableArray = require("tns-core-modules/data/observable-array");

const Observable = require("tns-core-modules/data/observable").Observable;
const fromObject = require("tns-core-modules/data/observable").fromObject;
const ObservableArray = require("tns-core-modules/data/observable-array")
  .ObservableArray;

var observablePeripheralArray = new observableArray.ObservableArray();
var peripherals = observablePeripheralArray;

var BarcodeScanner = require("nativescript-barcodescanner").BarcodeScanner;
var barcodescanner = new BarcodeScanner();

class Peripheral {
  constructor(name, UUID) {
    this.name = name;
    this.UUID = UUID;
  }
  name: string;
  UUID: string;
}

@Component({
  selector: "ns-home-page",
  templateUrl: "./home-page.component.html",
  styleUrls: ["./home-page.component.css"],
  moduleId: module.id
})
export class HomePageComponent implements OnInit {
  public peripheralsArray = new ObservableArray();

  constructor() {
    this.peripheralsArray.push(fromObject(new Peripheral("Device1", "34242")));
    this.peripheralsArray.push(fromObject(new Peripheral("Device2", "41244")));
    this.peripheralsArray.push(fromObject(new Peripheral("Device3", "24124")));
    this.peripheralsArray.push(fromObject(new Peripheral("Device4", "214124")));
    this.peripheralsArray.push(fromObject(new Peripheral("Device5", "214214")));
  }

  ngOnInit(): void {}

  doIsBluetoothEnabled() {
    bluetooth.isBluetoothEnabled().then(function(enabled) {
      dialogs.alert({
        title: "Bluetooth Enabled: ",
        message: enabled ? "Yes" : "No",
        okButtonText: "OK"
      });
    });
  }

  doEnableBluetooth() {
    bluetooth.enable().then(function(enabled) {
      setTimeout(function() {
        dialogs.alert({
          title: "Enable Bluetooth",
          message: enabled ? "Yes" : "No",
          okButtonText: "OK"
        });
      }, 500);
    });
  }

  // this one uses automatic permission handling
  doStartScanning() {
    // reset the array
    observablePeripheralArray.splice(0, observablePeripheralArray.length);
    bluetooth
      .startScanning({
        serviceUUIDs: [], // pass an empty array to scan for all services
        seconds: 6, // passing in seconds makes the plugin stop scanning after <seconds> seconds
        onDiscovered: function(peripheral) {
          observablePeripheralArray.push(observable.fromObject(peripheral));
          console.log(observablePeripheralArray);
          dialogs.alert({
            title: "Results",
            message: "Scanning is complete " + peripheral.UUID,
            okButtonText: "OK"
          });
        }
      })
      .then(
        function() {
          dialogs.alert({
            title: "Scanning is complete",
            message: "Scanning is complete",
            okButtonText: "OK"
          });
        },
        function(err) {
          dialogs.alert({
            title: "Error occured!",
            message: err,
            okButtonText: "OK"
          });
        }
      );
  }

  doStopScanning() {
    bluetooth.stopScanning().then(
      function() {
        dialogs.alert({
          title: "Stop Scanning",
          message: "Scanning is stopped",
          okButtonText: "OK"
        });
      },
      function(err) {
        dialogs.alert({
          title: "Error occured!",
          message: err,
          okButtonText: "OK"
        });
      }
    );
  }
}

【问题讨论】:

  • 您的 observablePeripheralArray 抛出错误。这就是为什么我的示例也没有加载的原因。将var observablePeripheralArray = new observableArray.ObservableArray(); var peripherals = observablePeripheralArray; 设为类字段,否则您无法在模板中引用它们。我的代码旨在说明如何去做。请重新加入聊天。
  • @etarhan 不再工作 :(

标签: javascript android angular typescript nativescript


【解决方案1】:

您的observablePeripheralArray 是在类之外定义的,它应该定义为类字段。以下是您应该如何构建组件的示例:

import { Component, OnInit } from "@angular/core";
const Observable = require("tns-core-modules/data/observable").Observable;
const fromObject = require("tns-core-modules/data/observable").fromObject;
const ObservableArray = require("tns-core-modules/data/observable-array").ObservableArray;

class Peripheral {
    constructor(name, UUID) {
        this.name = name;
        this.UUID = UUID;
    }
    name: string;
    UUID: string;
}

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ["./home.component.css"]
})
export class HomeComponent implements OnInit {
    public peripherals = new ObservableArray();
    constructor() {
        this.peripherals.push(fromObject(new Peripheral("Device1", "34242")));
        this.peripherals.push(fromObject(new Peripheral("Device2", "41244")));
        this.peripherals.push(fromObject(new Peripheral("Device3", "24124")))
        this.peripherals.push(fromObject(new Peripheral("Device4", "214124")))
        this.peripherals.push(fromObject(new Peripheral("Device5", "214214")))
    }

    ngOnInit(): void {
    }
}

标记:

<GridLayout>
    <ScrollView class="page">
        <StackLayout class="home-panel">
            <GridLayout rows="*">
                <ListView [items]="peripherals">
                    <ng-template let-peripheral="item" let-i="index" let-odd="odd"
                        let-even="even">
                        <StackLayout orientation="horizontal" class="list-group-item">
                            <Label [text]="peripheral.name"></Label>
                            <Label [text]="peripheral.UUID"></Label>
                        </StackLayout>
                    </ng-template>
                </ListView>
            </GridLayout>
        </StackLayout>
    </ScrollView>
</GridLayout>

在此处查看工作示例:https://play.nativescript.org/?template=play-ng&id=HYb8Ik

【讨论】:

  • 嗨!首先,感谢您的回复。不幸的是,列表视图中没有显示和列出项目。
  • 你能把[items]="observablePeripheralArray"改成[items]="observablePeripheralArray | async"吗?
  • 嗨。再次感谢你。我之前也查过这个帖子。我尝试了您的代码,但不幸的是它再次不起作用。 :-(
  • @KathrineHanson 它会抛出错误吗,你到底看到了什么?
  • 没有。它只是没有显示每个外围设备。警报 消息:“扫描完成” + peripheral.UUID 完美运行并向我显示每个外围设备。
猜你喜欢
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
相关资源
最近更新 更多