当前位置: 首页 > 工具软件 > amplify-cli > 使用案例 >

amplify aws_如何使用AWS Amplify和Angular构建启用云JavaScript应用程序

姬心思
2023-12-01

amplify aws

by Nader Dabit

纳德·达比特(Nader Dabit)

如何使用AWS Amplify和Angular构建启用云JavaScript应用程序 (How to use AWS Amplify and Angular to Build Cloud Enabled JavaScript Applications)

AWS Amplify helps you add functionality like storage, GraphQL, authentication, analytics, pub-sub, and internationalization to your JavaScript applications.

AWS Amplify可帮助您向JavaScript应用程序添加功能,如存储,GraphQL,身份验证,分析,发布订阅和国际化。

While you can integrate AWS Amplify into any JavaScript framework, Angular components have recently been added making it easier than before to get up and running with cloud services in an Angular application.

虽然您可以将AWS Amplify集成到任何 JavaScript框架中,但最近添加了Angular组件,从而比以前更容易在Angular应用程序中启动和运行云服务。

In this post, we’ll take a look at how to get up and running with AWS Amplify in an Angular application.

在本文中,我们将介绍如何在Angular应用程序中启动和运行AWS Amplify。

入门 (Getting Started)

安装依赖 (Installing dependencies)

To get started, we need in install a couple of dependencies: AWS Amplify and AWS Amplify Angular:

首先,我们需要安装几个依赖项:AWS Amplify和AWS Amplify Angular:

$ npm install --save aws-amplify
$ npm install --save aws-amplify-angular

创建一个新的AWS Mobile项目 (Creating a new AWS Mobile Project)

If you already have an AWS project you would like to use, you can skip this step. If not, you you will learn how we can use the AWS Mobile Hub to quickly get up and running with AWS services like Amazon Cognito for authentication, Amazon Pinpoint for analytics, AWS AppSync for managed GraphQL, and Amazon S3 for storage.

如果您已经有要使用的AWS项目,则可以跳过此步骤。 如果没有,您将学到如何使用AWS Mobile Hub快速启动并运行AWS服务,例如用于身份验证的Amazon Cognito,用于分析的Amazon Pinpoint,用于托管GraphQL的AWS AppSync和用于存储的Amazon S3。

The next thing we need to do here is install the AWS Mobile CLI:

我们在这里需要做的下一件事是安装AWS Mobile CLI:

npm i -g awsmobile-cli

Next, we will need to configure the AWS Mobile CLI to use your preferred IAM credentials.

接下来,我们将需要配置AWS Mobile CLI以使用您首选的IAM凭证。

If you are new to AWS and would like to see how to set this up for the first time, check out this video.

如果您不熟悉AWS,并且想首次了解如何进行设置,请观看视频。

awsmobile configure

Now, ourAWS Mobile CLI is ready to go and we can create a new project.

现在,我们的AWS Mobile CLI已准备就绪,我们可以创建一个新项目。

Let’s create a new project that has analytics, storage, and authentication enabled:

让我们创建一个启用了分析,存储和身份验证的新项目:

awsmobile init

awsmobile user-signin enable
awsmobile user-files enable
awsmobile push

After creating your backend, the configuration file is copied to /awsmobilejs/#current-backe

创建后端后,将配置文件复制到/awsmobilejs/#current-backe

在AWS控制台中查看您的项目 (Viewing your project in the AWS Console)

Now that you’ve created your project from the CLI, you can view your project in AWS Mobile hub by visiting https://console.aws.amazon.com/mobilehub/home and clicking on the name of your project.

现在,您已经从CLI创建了项目,您可以通过访问https://console.aws.amazon.com/mobilehub/home并单击项目名称,在AWS Mobile集线器中查看项目。

在Angular中工作 (Working in Angular)

To import the configuration file to your Angular app, you will need to rename aws_exports.js to aws_exports.ts.

要将配置文件导入到Angular应用中,您需要将aws_exports.js重命名为aws_exports.ts

To import the configuration file to your Angular app, you will need to rename aws_exports.js to aws_exports.ts.

要将配置文件导入到Angular应用中,您需要将aws_exports.js重命名为aws_exports.ts

import Amplify from 'aws-amplify'
import awsmobile from './aws-exports'
Amplify.configure(aws_exports)

When working with underlying aws-js-sdk, the “node” package should be included in types compiler option. Make sure that you edit the tsconfig.app.json file in your source file folder, e.g. src/tsconfig.app.json.

使用基础aws-js-sdk ,“ node”包应包含在类型编译器选项中。 确保在源文件文件夹中编辑tsconfig.app.json文件,例如src/tsconfig.app.json

"compilerOptions": {
  "types" : ["node"]
}

导入放大 (Importing Amplify)

In your root module src/app/app.module.ts, you can import AWS Amplify modules as following:

在您的根模块 src/app/app.module.ts ,您可以按以下方式导入AWS Amplify模块:

import { AmplifyAngularModule, AmplifyService } from 'aws-amplify-angular'

@NgModule({
  ...
  imports: [
    ...
    AmplifyAngularModule
  ],
  ...
  providers: [
    ...
    AmplifyService
  ]
  ...
})

The service provider is optional. You can import the core categories normally i.e. import { Analytics } from 'aws-amplify' or create your own provider. The service provider does some work for you and exposes the categories as methods. The provider also manages and dispatches authentication state changes using observables which you can subscribe to within your components (see below).

服务提供者是可选的。 您通常可以导入核心类别,即import { Analytics } from 'aws-amplify'或创建自己的提供程序。 服务提供商会为您做一些工作,并将类别作为方法公开。 提供程序还使用可观察到的内容来管理和调度身份验证状态更改,您可以在组件中订阅这些可观察到的内容(请参见下文)。

使用AWS Amplify服务 (Using the AWS Amplify Service)

AmplifyService is a provider in your Angular app, and it provides AWS Amplify core categories through dependency injection.

AmplifyService是Angular应用程序中的提供程序,它通过依赖项注入提供AWS Amplify核心类别。

To use AmplifyService with dependency injection, inject it into the constructor of any component or service, anywhere in your application.

要将AmplifyService依赖项注入一起使用, 请将其注入到应用程序中任何位置的任何组件或服务的构造函数中。

import { AmplifyService } from 'aws-amplify-angular';

...
constructor(
    public navCtrl:NavController,
    public amplifyService: AmplifyService,
    public modalCtrl: ModalController
) {
    this.amplifyService = amplifyService;
}
...

使用AWS Amplify类别 (Using AWS Amplify Categories)

You can access and work directly with AWS Amplify Categories via the built-in service provider:

您可以通过内置服务提供商访问和直接使用AWS Amplify类别:

import { Component } from '@angular/core';
import { AmplifyService }  from 'aws-amplify-angular';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  
  constructor( public amplify:AmplifyService ) {
      
      this.amplifyService = amplify;

      /** now you can access category APIs:
       * this.amplifyService.auth();          // AWS Amplify Auth
       * this.amplifyService.analytics();     // AWS Amplify Analytics
       * this.amplifyService.storage();       // AWS Amplify Storage
       * this.amplifyService.api();           // AWS Amplify API
       * this.amplifyService.cache();         // AWS Amplify Cache
       * this.amplifyService.pubsub();        // AWS Amplify PubSub
     **/
  }
  
}

使用示例:订阅身份验证状态更改 (Usage Example: Subscribe to Authentication State Changes)

Import AmplifyService into your component and listen for auth state changes:

将AmplifyService导入您的组件,并监听身份验证状态更改:

import { AmplifyService }  from 'aws-amplify-angular';

  // ...
constructor( public amplifyService: AmplifyService ) {

    this.amplifyService = amplifyService;

    this.amplifyService.authStateChange$
        .subscribe(authState => {
        this.signedIn = authState.state === 'signedIn';
        if (!authState.user) {
            this.user = null;
        } else {
            this.user = authState.user;
            this.greeting = "Hello " + this.user.username;
        }
        });

}

查看组件 (View Components)

AWS Amplify also provides components that you can use in your Angular view templates, including an authenticator component, a photo picker component, and an Amazon S3 album component.

AWS Amplify还提供了可在Angular视图模板中使用的组件,包括身份验证器组件,照片选择器组件和Amazon S3相册组件。

Authenticator

认证者

Authenticator component creates an out-of-the-box signing/sign-up experience for your Angular app. To use Authenticator, just add the amplify-authenticator directive in your .html view:

Authenticator组件可为您的Angular应用程序提供即用型的签名/注册体验。 要使用Authenticator,只需在.html视图中添加amplify-authenticator指令:

<amplify-authenticator></amplify-authenticator>

Photo Picker

照片选择器

Photo Picker component will render a file upload control that will allow choosing a local image and uploading it to Amazon S3. Once an image is selected, a base64 encoded image preview will be displayed automatically.

Photo Picker组件将呈现文件上传控件,该控件允许选择本地图像并将其上传到Amazon S3。 选择图像后,将自动显示base64编码的图像预览。

To render photo picker in an Angular view, use the amplify-photo-picker component:

要在“角度”视图中渲染照片选择器,请使用amplify-photo-picker组件:

<amplify-photo-picker 
    (picked)="onImagePicked($event)"
    (loaded)="onImageLoaded($event)">
</amplify-photo-picker>

The component will emit two events:

该组件将发出两个事件:

  • (picked) - Emitted when an image is selected. The event will contain the File object which can be used for upload.

    (picked) -选择图像时发射。 该事件将包含可用于上传的File对象。

  • (loaded) - Emitted when an image preview has been rendered and displayed.

    (loaded) -渲染并显示图像预览时发射。

Uploading an image

上载图片

Use onImagePicked(event) to upload your photo to Amazon S3 using AWS Amplify Storage category:

使用onImagePicked(event)使用AWS Amplify Storage类别将照片上传到Amazon S3:

onImagePicked( file ) {

    let key = `pics/${file.name}`;
    
    this.amplify.storage().put( key, file, {
      'level': 'private',
      'contentType': file.type
    })
    .then (result => console.log('uploaded: ', result))
    .catch(err => console.log('upload error: ', err));
  
}

S3专辑 (S3 Album)

The Amazon S3 Album component displays a list of images from the connected S3 bucket.

Amazon S3相册组件显示已连接的S3存储桶中的图像列表。

To render the album, use the amplify-s3-album component in your Angular view:

要渲染相册,请在Angular视图中使用amplify-s3-album组件:

<amplify-s3-album
  path="pics" (selected)="onAlbumImageSelected($event)"
>
</amplify-s3-album>

(selected) event can be used to retrieve the URL of the clicked image on the list:

(selected)事件可用于检索列表上单击的图像的URL:

onAlbumImageSelected( event ) {
      window.open( event, '_blank' );
}

Custom Styles

自定义样式

You can use custom styling for AWS Amplify components. Just import your custom styles.css that overrides the default styles which can be found in /node_modules/aws-amplify-angular/theme.css.

您可以对AWS Amplify组件使用自定义样式。 只需导入您的自定义styles.css即可覆盖/node_modules/aws-amplify-angular/theme.css可以找到的默认样式。

结论 (Conclusion)

AWS Amplify is open source and actively being developed, and we’d love any feedback and / or issues from customers or users to help us in our future roadmap.

AWS Amplify是开源的并且正在积极开发中,我们希望客户或用户的任何反馈和/或问题可以帮助我们制定未来的路线图。

Feel free to check out the docs here, or the GitHub repo here.

欢迎在此处查看文档,或在此处查看 GitHub存储库。

My Name is Nader Dabit . I am a Developer Advocate at AWS Mobile working with projects like AWS AppSync and AWS Amplify, and the founder of React Native Training.

我叫Nader Dabit 。 我是AWS Mobile的开发人员拥护者,负责AWS AppSyncAWS Amplify等项目,也是React Native Training的创始人。

翻译自: https://www.freecodecamp.org/news/building-cloud-enabled-javascript-applications-with-aws-amplify-angular-682547fc6477/

amplify aws

 类似资料: