使用AngularJS生成QR码

使用AngularJS生成QR码

在这篇文章中,我们将看到如何在我们的Angular应用程序中生成和显示QR码。二维码是一个由黑白方块组成的矩阵,可以通过相机或智能手机来读取。一个QR码可以存储信息和URL,使机器人或智能手机用户容易阅读。在商业场景中,二维码可用于分享联系信息、发送电子邮件、下载应用程序、分享URL和位置。因此,我们需要知道如何为我们的应用程序生成一个,以跟上市场的发展。

环境搭建:

安装angular CLI并创建一个新的angular项目。

npm i -g @angular/cli
ng new <project-name>
cd <project-name>

现在,通过在localhost上提供应用程序来验证安装。

ng serve -o

你应该看到angular的登陆页面,你就可以开始了。现在我们需要安装和注册一个额外的软件包。

npm install @techiediaries/ngx-qrcode

在app.module.ts中注册它。在app文件夹中的app.module.ts文件中修改或复制以下代码。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
  
// Import this module 
import {NgxQRCodeModule} from '@techiediaries/ngx-qrcode'
  
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxQRCodeModule    // Register the module
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在让我们创建一个新的组件来显示带有所需数据的QR码。

ng generate component qrcode

这将产生4个新文件。此外,它将通过自动注册组件来更新app.module.ts文件。现在在qrcode.component.ts中添加以下代码。

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-qrcode',
  templateUrl: './qrcode.component.html',
  styleUrls: ['./qrcode.component.css']
})
export class QrcodeComponent{ 
  elementType = 'url';
  data = 'https://geeksforgeeks.org/';
}

这里 elementType 可以是 ‘url’, ‘img’ 或 ‘canvas’。url类型可以编码字符串类型的数据。数据变量存储了我们要编码的数据。现在在qrcode.component.html中添加以下代码。

<ngx-qrcode
  [elementType]="elementType"
  [value]="data">
</ngx-qrcode>

我们使用了ngx-qrcode标签来放置一个组件。它将之前的数据作为输入。现在在app.component.html中添加这个组件。

<div>
  <app-qrcode></app-qrcode>
</div>

我们可以通过启动应用程序来检查它。

ng serve -o

在你的浏览器上打开http://localhost:4200/。你应该看到以下输出。你可以通过使用任何应用程序扫描代码来验证它。

使用AngularJS生成QR码

对JSON数据进行编码:我们也可以将JSON数据嵌入QR码中。首先,我们需要创建我们想要嵌入的对象。注意,当使用 “url “元素类型时,我们只能嵌入字符串数据。所以我们可以使用JSON.stringify()创建这个对象的字符串。请看下面qrcode.component.ts的代码来更好地理解。

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-qrcode',
  templateUrl: './qrcode.component.html',
  styleUrls: ['./qrcode.component.css']
})
export class QrcodeComponent{ 
  elementType = 'url';
  obj = {
    cellTowers: [
      {
        cellId: 170402199,
        locationAreaCode: 35632,
        mobileCountryCode: 310,
        mobileNetworkCode: 410,
        age: 0,
        signalStrength: -60,
        timingAdvance: 15
      }
    ]
  }
  data = JSON.stringify(this.obj);
}

输出:

使用AngularJS生成QR码

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程