angular 克隆_使用Angular和Stamplay构建Etsy克隆(第2部分)

angular 克隆

In Part 1 of our tutorial on How to Build an Etsy Clone, we got done with configuring Stamplay as the backend API for our entire application. We also integrated Facebook logins. And the best part about it, we did all of that without a single line of code!

在有关如何构建Etsy克隆的教程的第1部分中,我们完成了将Stamplay配置为整个应用程序的后端API的工作。 我们还集成了Facebook登录名。 最好的部分是,我们无需一行代码就能完成所有这些工作!

Let's pick up where we left off and move onto the front-end side of our application. This is where we get our hands dirty with HTML/CSS/JS. This is also where Angular comes heavily into play. The end of this chapter will look like:

让我们从停下来的地方开始,移到应用程序的前端。 这是我们使用HTML / CSS / JS的地方。 这也是Angular发挥重要作用的地方。 本章的结尾如下所示:

19-angular-etsy-stamplay-store-homefronnt

准备好项目 (Getting Your Project Ready)

If you go look at your new Stamplay application's home page, you'll see that Stamplay has laid out clear instructions to get started.

如果您查看新的Stamplay应用程序的主页,您会看到Stamplay列出了清晰的入门说明。

The steps are pretty much to grab the Stamplay CLI tools and then use those to push our project to Stamplay.

这些步骤几乎都是要获取Stamplay CLI工具,然后使用这些工具将我们的项目推送到Stamplay的。

安装图章工具 (Installing the Stamplay Tools)

Here are the steps that we'll follow along with:

以下是我们将遵循的步骤:

Note: You need Node.js installed to have npm available to you.

注意:您需要安装Node.js才能使用npm。

  1. Install Stamplay CLI tools: npm install -g stamplay-cli

    安装Stamplay CLI工具: npm install -g stamplay-cli
  2. Update the Stamplay tools: npm update -g stamplay-cli

    更新Stamplay工具: npm update -g stamplay-cli

Once we have the Stamplay tools, we can push our project up so that it is visible at <angularetsy.stamplayapp.com>.

一旦有了Stamplay工具,我们就可以向上推进项目,以便在<angularetsy.stamplayapp.com>上看到它。

部署我们的项目 (Deploying Our Project)

Let's initialize our Stamplay project with the following commands:

让我们使用以下命令初始化Stamplay项目:

  1. Choose a directory and start a Stamplay project:

    选择一个目录并启动一个Stamplay项目:
$ cd angular-etsy-stamplay
$ stamplay init

The stamplay init command will ask you for your App ID and Api key. Remember that these should be kept secret since the Api key provides god-like powers (full access to create, update, and delete content).

stamplay init命令将要求您提供App IDApi密钥 。 请记住,由于Api密钥具有类似神的功能(创建,更新和删除内容的完全访问权限),因此应将其保密。

01-angular-etsy-stamplay-init1

Your App ID will be the name of your application and the Api key can be found in your app's Stamplay dashboard:

您的应用程序ID将是您的应用程序名称,Api密钥可在您应用程序的Stamplay仪表板中找到:

02-angular-etsy-stamplay-api-key

Now we can try to deploy our application using:

现在,我们可以尝试使用以下方法部署应用程序:

$ stamplay deploy

03-angular-etsy-stamplay-deploy

By default, Stamplay sets the index.html file as the start for our application. This is set in the stamplay.json file that was created when we ran stamplay init.

默认情况下,Stamplay将index.html文件设置为我们的应用程序的开始。 这是在我们运行stamplay init时创建的stamplay.json文件中设置的。

Since we haven't our index.html file, Stamplay won't let us deploy. Let's start our application now and lay out the foundation of our Angular app.

由于我们还没有index.html文件,因此Stamplay不允许我们进行部署。 让我们现在开始我们的应用程序,并为Angular应用程序奠定基础。

开始我们的Angular应用 (Starting Our Angular Application)

Our Angular app will be very straightforward. We'll use ui-router for routing and have the following pages:

我们的Angular应用程序将非常简单。 我们将使用ui-router进行路由,并具有以下页面:

  • Home Page/Product Listings Page

    主页/产品列表页
  • Shop Page

    店铺页面
  • Shop Admin Page

    商店管理页面
  • Single Product Page

    单一产品页面
  • Checkout Page

    结帐页面
  • User Profile Page

    用户个人资料页面
  • Login/Signup Page

    登录/注册页面

With those pages in mind, let's get started.

考虑到这些页面,让我们开始吧。

目录结构 (Directory Structure)

Here is our directory structure for our Angular application. We'll be using Angular 1.x right now since 2.0 isn't fully production ready yet, but we'll be keeping our application structure similar to how you'd see an Angular 2.0 application to be handled.

这是Angular应用程序的目录结构。 由于2.0尚未完全投入生产,我们现在将使用Angular 1.x,但我们将保持我们的应用程序结构类似于您看到的Angular 2.0应用程序的处理方式。

|- index.html
|- style.css
|- app
    |- components
        |- admin
            |- admin.html
            |- admin.js
        |- authenticate
            |- authenticate.html
            |- authenticate.js
        |- home
            |- home.html
            |- home.js
        |- shop
            |- shop.html
            |- shop.js
        |- product
            |- product.html
            |- product.js
        |- checkout
            |- checkout.html
            |- checkout.js
        |- profile
            |- profile.html
            |- profile.js
    |- shared
        |- ProductService.js
        |- UserService.js
        |- OrderService.js
        |- ShopService.js
    |- app.routes.js
    |- app.js
|- bower.json

As you can see, we're keeping our structure close to the idea of components and WebComponents. This creates a solid separation for each part of our application.

如您所见,我们使我们的结构接近于组件和WebComponents的概念。 这为我们的应用程序的每个部分创建了坚实的隔离。

We're also creating the shared folder that will hold all of our Angular services that will talk to the Stamplay API.

我们还将创建shared文件夹,该文件夹将包含所有与Stamplay API通信的Angular服务。

Bower的前端依赖性 (Front-End Dependencies with Bower)

We're going to use Bower to grab the front-end resources we need. To install Bower, run the following:

我们将使用Bower来获取所需的前端资源。 要安装Bower,请运行以下命令:

$ npm install -g bower

For more info on Bower, read our Bower Getting Started tuorial . Now that we have bower installed, we just need to create a bower.json file by using the following command:

有关Bower的更多信息,请阅读我们的Bower入门入门教程 。 现在我们已经安装了bower,我们只需要使用以下命令来创建bower.json文件:

$ bower init

04-angular-etsy-bower-install

Just use the defaults here and then we can finally install our dependencies that we need. We will be using the following:

只需在此处使用默认值,我们就可以最终安装所需的依赖项。 我们将使用以下内容:

  • Bootswatch: (grabbing the Cerulean theme since that has an Etsy type of vibe)

    Bootswatch :(抢先使用Cerulean主题,因为它具有Etsy类型的氛围)
  • Stamplay SDK: This is the JavaScript SDK provided by Stamplay

    Stamplay SDK:这是Stamplay提供的JavaScript SDK
  • Angular

    角度的
  • ui-router: Angular routing

    ui-router:角路由
  • Angular Stamplay: A wrapper for the Stamplay SDK so that we can work with the proper commands in Angular

    Angular Stamplay :Stamplay SDK的包装,以便我们可以在Angular中使用适当的命令

To install all those in one command, run the following:

要将所有这些安装在一个命令中,请运行以下命令:

$ bower install --save bootswatch stamplay-js-sdk angular angular-stamplay ui-router

These will be installed into a new bower_components folder in the root of our project and we'll be able to reference those moving forward.

这些将被安装到我们项目根目录下的新bower_components文件夹中,我们将能够引用那些前进的目录。

The --save flag tells Bower to save these as dependencies in the bower.json file. This way, we have a centralized place to look when we need to know what front-end resources this application requires and what versions.

--save标志告诉Bower将它们保存为bower.json文件中的依赖bower.json 。 这样,当需要知道该应用程序需要哪些前端资源以及什么版本时,我们可以在一个集中的地方查看。

Related Reading: Only Grab the Files you Need with Bower

相关阅读: 通过Bower仅获取所需的文件

With all that ready to go, let's create our index.html file which will be the base for our entire application.

准备就绪后,让我们创建index.html文件,它将作为整个应用程序的基础。

启动我们的主视图文件(index.html) (Starting Our Main View File (index.html))

Let's create all those files now and take a look at our index.html file.

现在让我们创建所有这些文件,并查看我们的index.html文件。

index.html (index.html)

In this file, the main things we have to do are load all of our dependencies (app.js and style.css) and make sure we configure our Stamplay application.

在此文件中,我们要做的主要事情是加载所有依赖项( app.jsstyle.css ),并确保我们配置Stamplay应用程序。

We're also going to lay out our overall application with a header, footer, and the main section where Angular and ui-router will inject our views.

我们还将用headerfooter和Angular和ui-router注入我们的视图的主要部分来布局整个应用程序。

Here is the start of our index.html file:

这是我们的index.html文件的开始:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular Etsy Stamplay</title>

    <!-- required by ui-router -->
    <base href="/">

    <!-- CSS -->
    <!-- load up bootswatch-cerulean and our custom styles -->

    <!-- JS -->
    <!-- load the stamplay sdk and configure it -->

</head>
<body>

</body>
</html>

Let's go piece by piece and fill in the blanks.

让我们一步一步去填补空白。

添加CSS文件 (Adding CSS Files)

We're loading the Cerulean Bootswatch theme and our own style.css file that we created earlier.

我们正在加载Cerulean Bootswatch主题和我们先前创建的我们自己的style.css文件。

<!-- index.html -->
<!-- CSS -->
<!-- load up bootswatch-cerulean and our custom styles -->
<link rel="stylesheet" href="./bower_components/bootswatch/cerulean/bootstrap.min.css">
<link rel="stylesheet" href="./style.css">
添加JS文件 (Adding JS Files)

This will seem the most daunting at first. But we're going to take it piece by piece. And remember, in a production level application, you'd want to use a task runner like Grunt or Gulp to minify and combine/concatenate all these files together into one singular file.

起初这似乎是最艰巨的。 但是,我们将逐步解决它。 记住,在生产级应用程序中,您想使用任务运行程序(例如GruntGulp)来将所有这些文件最小化并将其组合/合并为一个单一文件。

<!-- index.html -->
<!-- JS -->
<!-- load the stamplay sdk and configure it -->
<script src="./bower_components/stamplay-js-sdk/dist/stamplay.min.js"></script>
<script>
    Stamplay.init('angularetsy');   // initiate stamplay app with app name
</script>

<!-- load our other JS dependencies -->
<script src="./bower_components/angular/angular.min.js"></script>
<script src="./bower_components/angular-stamplay/angular-stamplay.js"></script>
<script src="./bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>

<!-- load all the parts for our custom angular app -->
<!-- youd probably want to compile all this with a build system like gulp -->
<!-- load our angular components -->
<script src="./app/components/home/home.js"></script>
<script src="./app/components/shop/shop.js"></script>
<script src="./app/components/product/product.js"></script>
<script src="./app/components/checkout/checkout.js"></script>
<script src="./app/components/profile/profile.js"></script>
<script src="./app/components/admin/admin.js"></script>
<script src="./app/components/authenticate/authenticate.js"></script>

<!-- load our angular services -->
<script src="./app/shared/ProductService.js"></script>
<script src="./app/shared/UserService.js"></script>
<script src="./app/shared/OrderService.js"></script>
<script src="./app/shared/ShopService.js"></script>

<!-- load our core angular app -->
<script src="./app/app.routes.js"></script>
<script src="./app/app.js"></script>

Wow what a doozy. That may seem like a lot of loading things, but again, you'd want a way to automate all this together in the future.

哇,真是个傻瓜。 看起来好像很多东西都在加载,但是同样,您希望将来有一种方法可以使所有这些自动化。

We're just loading the Stamplay JS SDK and configuring that with our application name. Then we're loading the different pieces of our Angular application. We'll bootstrap all that together soon.

我们只是加载Stamplay JS SDK并使用我们的应用程序名称对其进行配置。 然后,我们加载Angular应用程序的不同部分。 我们将尽快将所有内容一起引导。

Let's keep moving with this index.html file and move to the <body>.

让我们继续移动这个index.html文件,然后移到<body>

主体 (The Main Body)

We're going to need a <header>, <main>, and <footer> so let's create those:

我们将需要一个<header><main><footer>因此让我们创建它们:

<!-- index.html -->
<!-- HEADER AND NAV -->
<header>
    <nav id="main-nav" class="navbar">
    <div class="container">

        <!-- site logo -->
        <div class="navbar-header">
            <a href="#" class="navbar-brand">
                <span class="glyphicon glyphicon-heart-empty"></span>
                Shop City
            </a>
        </div>

        <!-- search form -->
        <form class="navbar-form navbar-left">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-primary">Search</button>
        </form>

        <!-- logged in navigation -->
        <!-- todo: check for logged in user -->
        <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Admin</a></li>
            <li><a href="#">Purchases</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Logout</a></li>
        </ul>

        <!-- not logged in navigation -->
        <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Register</a></li>
            <li><a href="#">Sign in</a></li>
        </ul>
    </div>
    </nav>
</header>

<!-- ui-router will inject our component views here -->
<main class="container">
    <div ui-view></div>
</main>

<!-- FOOTER -->
<footer class="text-center">
    © 2015 Shop City
</footer>

Most of this is Bootstrap stylings and we'll be filling in the link hrefs (or ui-srefs in our case since we're using ui-router) once we have our Angular routes configured.

其中大多数是Bootstrap hrefs一旦配置了Angular路由,我们将填写链接hrefs (或本例中的ui-sref ,因为我们使用的是ui-router )。

We'll also be using Angular to show/hide those logged in links if a user is not logged in via Stamplay.

如果用户未通过Stamplay登录,我们还将使用Angular显示/隐藏那些已登录的链接。

一些快速样式 (Some Quick Styling)

Now let's add a little styling so that we sort of look like Etsy. The Cerulean theme has this crazy blue navbar that we're going to get rid of. Etsy also uses a serif font for their headers so we'll do the same.

现在让我们添加一些样式,使我们看起来像Etsy。 Cerulean主题具有我们将要摆脱的这个疯狂的蓝色导航栏。 Etsy的标题也使用了衬线字体,因此我们将做同样的事情。

In our style.css file, add the following:

在我们的style.css文件中,添加以下内容:

/* style.css */
/* main styles ------------------------------------------*/
body        {
    background:#EFEFEF;
}

h1, h2, h3, h4, h5, h6  {
    font-family:Georgia, serif;
}

/* footer ---------------------------------------------- */
footer      { padding-top:50px; }

/* header ---------------------------------------------- */
#main-nav   {
    background:#FFF;
    background-image:none;
    border:none;
    border-bottom:1px solid #E1E3DF;
    box-shadow:none;
}

/* logo */
#main-nav .navbar-brand     {
    color:#f45800;
    font-size:30px;
    padding-top:20px;
    padding-bottom:20px;
    font-family:Georgia, serif;
}

/* nav links */
#main-nav a     {
    font-size:18px;
    padding-bottom:30px;
    padding-top:30px;
}
#main-nav a:hover   {
    background:none;
}

/* header search form */
#main-nav .navbar-form  {
    padding-top:16px;
    padding-bottom:10px;
}

测试我们的主视图 (Testing Our Main View)

Now that we have all that wired up, let's see how it looks! We're going to need a local server to view our application (or you can just stamplay deploy) and see it live.

现在我们已经完成了所有的工作,让我们看看它的外观! 我们将需要一个本地服务器来查看我们的应用程序(或者您可以只是stamplay deploy )并实时查看它。

Luckily, Stamplay also has a command to get a local server up for us to test. All we have to do is run:

幸运的是,Stamplay还具有一个命令来启动本地服务器供我们测试。 我们要做的就是运行:

$ stamplay start

Then my app is viewable at http://localhost:8080.

然后可以在http:// localhost:8080上查看我的应用程序。

05-angular-etsy-stamplay-index-first

部署到Stamplay (Deploying to Stamplay)

Great! Our foundation is ready! Let's move on to wiring up all our views and components together so we can click around our application and see the pages changing.

大! 我们的基础已经准备好! 让我们继续将所有视图和组件连接在一起,以便我们可以在应用程序中单击并查看页面更改。

Go ahead and stamplay deploy and we can also see our application live at http://angularetsy.stamplayapp.com! If you want to share it with people, feel free. It doesn't do much yet but it will very soon.

继续进行stamplay deploy ,我们还可以在http://angularetsy.stamplayapp.com上实时查看我们的应用程序! 如果您想与人分享,请放心。 它并没有做很多,但很快就会完成。

06-angular-etsy-stamplay-first-deploy
image

图片

针对我们的应用的角路由 (Angular Routing for Our Application)

Our application doesn't really do much yet, but let's start working on the Angular side of things to get all the functionality that we want. We're going to be using ui-router so if you need a primer on that, be sure to read our Angular Routing with ui-router article.

我们的应用程序还没有真正做很多事情,但是让我们开始在Angular方面进行工作,以获得我们想要的所有功能。 我们将使用ui-router,因此,如果您需要使用ui-router ,请务必阅读我们的《 使用ui-router进行角路由 》。

We've already grabbed Angular and ui-router using Bower and have already loaded it into our application in index.html. The next step is to start up our app.js file.

我们已经使用Bower抓取了Angular和ui-router,并已将它加载到index.html的应用程序中。 下一步是启动我们的app.js文件。

启动我们的Angular应用(app.js) (Starting Our Angular App (app.js))

Here we will create our angular.module and create a MainController to encompass our entire application.

在这里,我们将创建angular.module并创建一个MainController来包含整个应用程序。

// app.js
angular
    .module('etsyApp', [
        'ngStamplay',
        'ui.router',
        'app.routes'
    ])
    .controller('MainController', MainController);

/**
 * The main controller for our application
 */
function MainController() {
    var main = this;

}

We've started our etsyApp and injected ngStamplay, ui.router and the app.routes module (we haven't created it just yet). We've also created a MainController that we can use to house things that will be usable all around our application.

我们已经启动了etsyApp并注入了ngStamplayui.routerapp.routes模块(我们尚未创建它)。 我们还创建了一个MainController ,可以用来容纳在整个应用程序中都可以使用的东西。

Things like the logout functionality can go here. Now we have to apply our Angular application to our view. We will do that in index.html on the <body> tag:

诸如注销功能之类的东西可以在这里进行。 现在,我们必须将Angular应用程序应用于我们的视图。 我们将在index.html<body>标记上执行此操作:

<!-- index.html -->
...
<body ng-app="etsyApp" ng-controller="MainController as main">
...

Our Angular application is now applied to our view. If we try to view this in our browser, we'll throw an error however since we haven't yet defined the app.routes module in the app.routes.js file.

现在将Angular应用程序应用于我们的视图。 如果尝试在浏览器中查看此内容,则会由于我们尚未在app.routes.js文件中定义app.routes模块而抛出错误。

创建我们的路由文件 (Creating Our Routing File)

The routing file may be one of the most important (if not the most important) file in our entire Angular application. It is the backbone of our application and is a top-level view of how things will work together. It will define the pages of our application, grab all the necessary views, and assign the proper controllers.

路由文件可能是整个Angular应用程序中最重要(如果不是最重要)的文件之一。 它是我们应用程序的基础,并且是事物如何协同工作的顶层视图。 它将定义应用程序的页面,获取所有必要的视图,并分配适当的控制器。

This is going to be a lot, but let's parse through it and see what's happening in app.routes.js:

这会很多,但是让我们分析一下,看看app.routes.js发生了app.routes.js

// app.routes.js
angular
    .module('app.routes', [])
    .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', AppRoutes]);

/**
 * Create all the application routes
 */
function AppRoutes($stateProvider, $urlRouterProvider, $locationProvider) {

    // pretty Angular URLs
    $locationProvider.html5Mode(true);

    // the route people are sent to when they are lost
    // the home page in this case
    $urlRouterProvider.otherwise('/');

    // create our routes, set the view, pull in the controller
    $stateProvider

        // home page
        .state('home', {
            url         : '/',
            templateUrl : '/app/components/home/home.html',
            controller  : 'HomeController as home'
        })

        // shop page
        .state('shop', {
            url         : '/shop/{name}',
            templateUrl : '/app/components/shop/shop.html',
            controller  : 'ShopController as shop'
        })

        // product page (a child of shop)
        .state('product', {
            url         : '/listing/{id}/{name}',
            templateUrl : '/app/components/product/product.html',
            controller  : 'ProductController as product'
        })

        // login/signup page
        .state('authenticate', {
            url         : '/authenticate',
            templateUrl : '/app/components/authenticate/authenticate.html',
            controller  : 'AuthenticateController as authenticate'
        })

        // profile page
        .state('profile', {
            url         : '/profile/{user_name}',
            templateUrl : '/app/components/profile/profile.html',
            controller  : 'ProfileController as profile'
        })

        // checkout page
        .state('checkout', {
            url         : '/checkout/{id}',
            templateUrl : '/app/components/checkout/checkout.html',
            controller  : 'CheckoutController as checkout'
        })

        // checkout page
        .state('admin', {
            url         : '/admin',
            templateUrl : '/app/components/admin/admin.html',
            controller  : 'AdminController as admin'
        });
}

It really just feels like a lot because it's the longest file we've made so far, but it's very straightforward.

感觉确实很不错,因为它是我们到目前为止制作的最长的文件,但是非常简单。

  • Create a route

    建立路线
  • Pick the view file associated with it

    选择与其关联的视图文件
  • Pick the Angular controller associated with that view

    选择与该视图关联的Angular控制器

This keeps to the idea that each part of our site is a component and gets us in the mindset for Angular 2 when that happens in the future.

这使我们的想法保持不变,即网站的每个部分都是一个组件,并在将来发生这种情况时将我们带入Angular 2的思维定式。

Note: If you're wondering why I define the .config() like that, it's for minification purposes. Read more: Declaring AngularJS Modules for Minification

注意:如果您想知道为什么要这样定义.config() ,它是为了缩小目的。 阅读更多: 声明用于缩小的AngularJS模块

Then we set the $urlRouterProvider.otherwise() to let our application know where to route people if they are trying to access a route that doesn't exist.

然后,我们设置$urlRouterProvider.otherwise()来让我们的应用程序知道人们在尝试访问不存在的路由时将其路由到何处。

We're setting two URL parameters on product because we don't want to limit product name to be unique (multiple users should be able to create the same product name) and we're going to use the id since that will always be unique.

我们在product上设置了两个URL参数,因为我们不想将产品名称限制为唯一(多个用户应能够创建相同的产品名称),并且我们将使用id因为该名称始终是唯一的。

Now that we have these routes, we have to tell our application's links to use them. Earlier, we just defined our <a> tags with href="#" so they won't do anything.

现在我们有了这些路由,我们必须告诉应用程序的链接以使用它们。 之前,我们只是用href="#"定义了<a>标记,因此它们不会做任何事情。

将我们的应用程序链接在一起 (Linking Together Our Application)

In ui-router, the way we define links is to use ui-sref and then point to the name of the state.

在ui-router中,定义链接的方法是使用ui-sref ,然后指向状态名称。

Here is our updated index.html file (just the <header> part).

这是我们更新的index.html文件(只是<header>部分)。

<!-- index.html -->
<!-- HEADER AND NAV -->
<header>
    <nav id="main-nav" class="navbar">
    <div class="container">

        <!-- site logo -->
        <div class="navbar-header">
            <a ui-sref="home" class="navbar-brand">
                <span class="glyphicon glyphicon-heart-empty"></span>
                Shop City
            </a>
        </div>

        <!-- search form -->
        <form class="navbar-form navbar-left">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-primary">Search</button>
        </form>

        <!-- logged in navigation -->
        <!-- todo: check for logged in user -->
        <ul class="nav navbar-nav navbar-right">
            <li><a ui-sref="admin">Admin</a></li>
            <li><a ui-sref="profile">Profile</a></li>
            <li><a href="#">Logout</a></li>
        </ul>

        <!-- not logged in navigation -->
        <ul class="nav navbar-nav navbar-right">
            <li><a ui-sref="authenticate">Register</a></li>
            <li><a ui-sref="authenticate">Sign in</a></li>
        </ul>
    </div>
    </nav>
</header>

Now you may ask why did we remove the href="#" from our links? Well when having an href="#", this will cause the browser to move to the top when clicked (an anchor to the top of the page). We'll just use the ui-sref and add some CSS so that our users will see the cursor on our a tags.

现在您可能会问为什么我们从链接中删除href="#" ? 好吧,当具有href="#" ,这将导致浏览器在单击时移动到顶部(页面顶部的锚点)。 我们将只使用ui-sref并添加一些CSS,以便我们的用户可以在我们的a标签上看到光标。

Add this to your style.css file:

将此添加到您的style.css文件中:

/* style.css */
/* make sure that our a tags have the cursor */
a[ui-sref]  { cursor:pointer; }

We also haven't added a ui-sref to the Logout button because that will be handled with an ng-click from our MainController. We'll deal with that after we have login functionality working in a few sections.

我们还没有在Logout按钮中添加ui-sref ,因为这将通过从MainController ng-click来处理。 我们将在几节中介绍登录功能后再进行处理。

创建组件 (Creating The Components)

We've used our routing to point to the specific components like app/components/home/home.js but we haven't defined that Angular controller yet. Let's do that for each of our files. Just go in and drop the following into each file. This will be the base template for each.

我们已经使用路由来指向诸如app/components/home/home.js类的特定组件,但尚未定义Angular控制器。 让我们为每个文件执行此操作。 只需将以下内容放入每个文件即可。 这将是每个的基本模板。

app / components / home / home.js (app/components/home/home.js)
// home.js
angular
    .module('app.home', [])
    .controller('HomeController', HomeController);

function HomeController() {
    var home = this;
}
app / components / admin / admin.js (app/components/admin/admin.js)
// admin.js
angular
    .module('app.admin', [])
    .controller('AdminController', AdminController);

function AdminController() {
    var admin = this;
}
app / components / authenticate / authenticate.js (app/components/authenticate/authenticate.js)
// authenticate.js
angular
    .module('app.authenticate', [])
    .controller('AuthenticateController', AuthenticateController);

function AuthenticateController() {
    var authenticate = this;
}
app / components / checkout / checkout.js (app/components/checkout/checkout.js)
// checkout.js
angular
    .module('app.checkout', [])
    .controller('CheckoutController', CheckoutController);

function CheckoutController() {
    var checkout = this;
}
app / components / product / product.js (app/components/product/product.js)
// product.js
angular
    .module('app.product', [])
    .controller('ProductController', ProductController);

function ProductController() {
    var product = this;
}
app / components / profile / profile.js (app/components/profile/profile.js)
// profile.js
angular
    .module('app.profile', [])
    .controller('ProfileController', ProfileController);

function ProfileController() {
    var profile = this;
}

With all those defined as our controllers, ui-router will know which to pull for a certain view now. All we have to do is inject them into our main application now.

将所有这些定义为我们的控制器后,ui-router现在将知道为某个视图拉入哪个。 我们要做的就是现在将它们注入到我们的主应用程序中。

注入主应用程序 (Injecting into the Main Application)

Go into the app.js file and inject the following into the dependencies:

进入app.js文件,并将以下内容注入依赖项:

// app.js
angular
    .module('etsyApp', [
        'ngStamplay',
        'ui.router',
        'app.routes',
        'app.admin',
        'app.authenticate',
        'app.checkout',
        'app.home',
        'app.product',
        'app.profile',
        'app.shop'
    ])

Finally our entire application is set up and ready to rock. We can now go piece by piece and start working on each module as we fill out the functionality in our application.

最终,我们的整个应用程序都已设置好并准备就绪。 现在,当我们在应用程序中填写功能时,我们可以逐步进行并开始处理每个模块。

Let's test to make sure that everything is working and go to your application in browser. You should be able to click around and see the URL changing.

我们进行测试以确保一切正常,然后在浏览器中转到您的应用程序。 您应该可以单击查看URL的变化。

07-angular-etsy-stamplay-routing-ready

We can fill in each view now so that we can show things to our users. The next step is to create Angular services to talk to our Stamplay backend.

我们现在可以填写每个视图,以便向用户显示内容。 下一步是创建Angular服务以与我们的Stamplay后端进行对话。

Angular Services与我们的Stamplay API进行交互 (Angular Services to Interact with Our Stamplay API)

If routing is the backbone of our application, then the services are our communication network. These are how we will talk to the Stamplay API that was created in Part 1.

如果路由是我们应用程序的基础,那么服务就是我们的通信网络 。 这些就是我们将与第1部分中创建的Stamplay API进行通信的方式。

We'll use a UserService to authenticate and register users via their email.

我们将使用UserService通过用户的电子邮件进行身份验证和注册。

We'll also use a ProductService to show all products and let users create products. Then we'll create a ShopService to let users create their own shops if they choose to do so.

我们还将使用ProductService展示所有产品,并让用户创建产品。 然后,我们将创建一个ShopService ,让用户选择创建自己的商店。

Let's get started with our UserService. A lot of the functionality in this has been provided to us by the Stamplay JS SDK and the angular-stamplay module.

让我们开始使用UserService 。 Stamplay JS SDK和angular-stamplay模块已为我们提供了许多功能。

认证用户服务 (User Service for Authentication)

The main functions in our UserService will be:

我们的UserService的主要功能将是:

  • Get the current logged in user

    获取当前登录的用户
  • Register a user

    注册用户
  • Log a user in

    登录用户
  • Log a user out

    注销用户

Here is the app/shared/UserService.js file:

这是app/shared/UserService.js文件:

// UserService.js
angular
    .module('UserService', [])
    .factory('User', ['$stamplay', '$q', UserService]);

function UserService($stamplay, $q) {

    // return an object with all our functions
    return {
        getCurrent: getCurrent,
        signup: signup,
        login: login,
        logout: logout
    };

    /**
     * Get the current logged in user
     */
    function getCurrent() {
        var def = $q.defer();

        // instantiate a new user model from the stamplay js sdk
        var user = $stamplay.User().Model;
        user.currentUser()
            .then(function() {
                // send the entire user model back
                def.resolve(user);
            });

        return def.promise;
    }

    /**
     * Register a user with their name, email, and password
     */
    function signup(data) {
        var def = $q.defer();

        // instantiate a new user model from the stamplay js sdk
        var user = $stamplay.User().Model;
        user.signup(data)
            .then(function() {
                // send the entire user model back
                def.resolve(user);
            })

        return def.promise;
    }

    /**
     * Log a user in with their email and password
     */
    function login(data) {
        var def = $q.defer();

        var user = $stamplay.User().Model;
        user.login(data.email, data.password)
            .then(function() {
                // send the entire user model back
                def.resolve(user);
            }, function() {
                def.reject({ 'error': 'Unable to login user.' });
            });

        return def.promise;
    }

    /**
     * Log the current user out
     * Will also redirect the browser to the logout url (home)
     */
    function logout() {
        var user = $stamplay.User().Model;
        user.logout();
    }

}

We have four main functions here: getCurrent, signup, login, and logout. The format for these are very similar. We are going to use the Stamplay JS SDK to grab what we need. Stamplay provides a convenient wrapper so that we don't have to worry about the internals of what's going on.

这里有四个主要功能: getCurrentsignuploginlogout 。 这些格式非常相似。 我们将使用Stamplay JS SDK来获取我们需要的东西。 Stamplay提供了一个方便的包装器,因此我们不必担心正在发生的事情的内部。

For instance, for the signup function, we just need to pass in an email, a password, and a displayName and that user will be created. We will then return the user object in a promise object so that we will be able to use it in our controllers.

例如,对于signup功能,我们只需要传递emailpassworddisplayName创建该用户。 然后,我们将在promise对象中返回用户对象,以便能够在控制器中使用它。

With this UserService ready to go, we can go and inject it into our main app.js file and then use it in our authenticate component. Let's inject it and move on:

准备好此UserService ,我们可以将其注入到主app.js文件中,然后在我们的authenticate组件中使用它。 让我们注入它并继续:

// app.js
angular
    .module('etsyApp', [
        ... 
        'UserService'
        ...
    ])

Now that we have it, we can inject the User factory into our MainController like so:

现在有了它,我们可以将User工厂注入到MainController如下所示:

// app.js
    .controller('MainController', ['User', '$rootScope', MainController]);

function MainController(User, $rootScope) {
    ...
}

We are also grabbing $rootScope so that we can bind the logged in user to that and have it usable across our application. Next step is to actually use this new User factory.

我们还抓住了$rootScope以便我们可以将登录用户绑定到该用户,并使其在我们的应用程序中可用。 下一步是实际使用这个新的User工厂。

抓住当前用户 (Grabbing The Current User)

When a user lands on our application, we will want to show that they are logged in if they are. To do this, we will need to grab the current user's logged in information. We have already created the function to do so in our UserService so let's use it in the MainController.

当用户登陆我们的应用程序时,我们将希望表明他们已经登录。 为此,我们需要获取当前用户的登录信息。 我们已经在UserService创建了用于执行此操作的函数,因此让我们在MainController使用它。

// app.js
function MainController(User) {
  var main         = this;
  $rootScope.currentUser = {}; // creating this object to hold our current users info

  // get the current user and bind their data to $rootScope.currentUser object
  User.getCurrent()
    .then(function(data) {
      if (data.get('_id')) {
        $rootScope.currentUser.id    = data.get('_id');
        $rootScope.currentUser.name  = data.get('displayName');
        $rootScope.currentUser.image = data.get('profileImg');
      } else {
        // clear the current user just to be sure
        $rootScope.currentUser = {};
      }
    });
}

Now that we are grabbing a logged in user (if there is one) and binding it to the $rootScope.currentUser object, we can use that object in our view to hide/show certain elements of our UI.

现在,我们正在获取一个登录用户(如果有)并将其绑定到$rootScope.currentUser对象,我们可以在视图中使用该对象来隐藏/显示UI的某些元素。

Note: If you are testing your application locally, then you'll see that there is an error running User.getCurrent(). This is because Stamplays CORS security only allows access from specified domains. View the Stamplay CORS Policy to see how you can add your local domain to your application and have the ability to test locally.

注意:如果要在本地测试应用程序,则会看到运行User.getCurrent()出错。 这是因为Stamplays CORS安全性仅允许来自指定域的访问。 查看Stamplay CORS政策,以了解如何将本地域添加到应用程序中并具有在本地进行测试的能力。

根据登录状态隐藏UI元素 (Hiding UI Elements Based on Logged In Status)

Let's hide all the things that require a login in our index.html file.

让我们在index.html文件中隐藏所有需要登录的内容。

We will use ngShow and ngHide on our <ul> tags.

我们将在<ul>标签上使用ngShow和ngHide

<!-- index.html -->
<!-- logged in navigation -->
<!-- todo: check for logged in user -->
<ul class="nav navbar-nav navbar-right" ng-show="currentUser.id">
  <li><a ui-sref="admin">Admin</a></li>
  <li><a ui-sref="profile">Profile</a></li>
  <li><a href="#">Logout</a></li>
</ul>

<!-- not logged in navigation -->
<ul class="nav navbar-nav navbar-right" ng-show="!currentUser.id">
    <li><a ui-sref="authenticate">Register</a></li>
    <li><a ui-sref="authenticate">Sign in</a></li>
</ul>

Very straightforward here. We are going to show the logged in links if there is a user bound to currentUser (which looks at $rootScope) and show the logged out links if one doesn't exist.

这里很简单。 如果有一个绑定到currentUser的用户(显示为$rootScope ),我们将显示已登录的链接,如果不存在则显示已注销的链接。

注销用户 (Logging a User Out)

Let's wire up that Logout button now that we have the functionality from our UserService.

现在,我们可以使用UserService的功能连接“ 注销”按钮。

We just need to add a function to our MainController:

我们只需要向MainController添加一个函数:

// app.js
function MainController(User, $rootScope) {
  var main = this;
  main.logout = logout; // bind the logout function to our controller

  ...

  /**
   * Use the User factory's logout functionality
   */
  function logout() {
    User.logout();
    $rootScope.currentUser = {};
  }  
}

Let's add that to our Logout button in index.html now:

现在,将其添加到index.html的“ 注销”按钮中:

<!-- index.html -->
<li><a ng-click="main.logout()">Logout</a></li>

And a little CSS to make sure that a user has their cursor when they hover ng-click:

还有一点CSS,以确保用户将鼠标悬停在ng-click时具有光标:

/* style.css */
/* make sure that our a tags have the cursor */
a[ui-sref],
a[ng-click]  { cursor:pointer; }

Great! Now we have everything needed for when a user is logged in. But how will they login if they don't have an account yet? Let's move onto our authenticate page where a user will be able to sign up with their email address.

大! 现在,我们拥有用户登录时所需的一切。但是,如果他们还没有帐户,他们将如何登录? 让我们进入我们的authenticate页面,用户可以在其中使用其电子邮件地址进行注册。

处理电子邮件登录和注册 (Handling Email Login and Signup)

We already have Facebook login and signup thanks to Stamplay. Now we will use their JS SDK tools to let our users sign up and login with their email address.

感谢Stamplay,我们已经可以登录和注册Facebook。 现在,我们将使用他们的JS SDK工具让我们的用户注册并使用其电子邮件地址登录。

This will all be handled in our UserService.js file. We'll then pull that service into the authenticate.js component of our application and let people login and signup there.

所有这些都将在我们的UserService.js文件中处理。 然后,我们将该服务拉入我们应用程序的authenticate.js组件中,并让人们在此处登录和注册。

登录/注册视图 (Login/Signup View)

In our authenticate.html file is where we will create the view for our login/signup page. We'll be splitting the page in half, left side for signup and right side for login.

在我们的authenticate.html文件中,我们将为登录/注册页面创建视图。 我们将页面分为两半,左侧为注册,右侧为登录。

08-angular-etsy-stamplay-signup

Here is the code in app/components/authenticate/authenticate.html:

这是app/components/authenticate/authenticate.html的代码:

<!-- authenticate.html -->
<div class="row">

  <!-- SIGNUP =============================== -->
  <div class="col-sm-6">
    <div class="page-header text-center">
      <h2>Sign Up</h2>
    </div>

    <!-- signup button to use facebook -->
    <p>
      <a class="btn btn-block btn-primary" href="/auth/v1/facebook/connect">Sign Up with Facebook</a>
    </p>

    <!-- form will use authenticate.signup on submit -->
    <form id="signupForm" ng-submit="authenticate.signup()">
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" ng-model="authenticate.signupData.displayName" required>
      </div>

      <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" ng-model="authenticate.signupData.email" required>
      </div>

      <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" ng-model="authenticate.signupData.password" required>
      </div>

      <button type="submit" class="btn btn-info">Sign Up</button>
    </form>
  </div>

  <!-- LOGIN ================================ -->
  <div class="col-sm-6">
    <div class="page-header text-center">
      <h2>Login</h2>
    </div>

    <!-- signup button to use facebook -->
    <p>
      <a class="btn btn-block btn-primary" href="/auth/v1/facebook/connect">Login with Facebook</a>
    </p>

    <!-- form will use authenticate.login on submit -->
    <form id="loginForm" ng-submit="authenticate.login()">
      <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" ng-model="authenticate.loginData.email" required>
      </div>

      <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" ng-model="authenticate.loginData.password" required>
      </div>

      <button type="submit" class="btn btn-info">Login</button>
    </form>
  </div>
</div>

This is very Bootstrap heavy syntax which is totally fine since it helps us get to our end goal faster. We're going to create a signupForm and a loginForm here with each one bound to a separate function in the AuthenticateController. We'll be defining both of those soon.

这是非常严格的Bootstrap语法,因为它可以帮助我们更快地达到最终目标,因此完全可以。 我们将在这里创建一个signupForm和一个loginForm ,每个绑定到AuthenticateController中的一个单独函数。 我们将很快定义两者。

Notice we also created links to the Login with Facebook. This link is the same as the Sign Up with Facebook as the flow for that is the same. If a Facebook user exists in our database, Stamplay will return them, if not, Stamplay will create them.

注意,我们还创建了指向“使用Facebook 登录”的链接。 此链接与使用Facebook 注册”相同,因为其流程相同。 如果我们的数据库中存在Facebook用户,Stamplay将返回它们,否则,Stamplay将创建它们。

Notice we also bind each form's data to a specific object on our AuthenticateController (signupData and loginData).

注意,我们还将每个表单的数据绑定到AuthenticateController上的特定对象( signupDataloginData )。

Let's move forward and create the controller that will handle submitting both of these forms.

让我们继续前进,创建一个控制器来处理这两种形式的提交。

验证控制器 (Authenticate Controller)

First thing we need to do is inject the User factory into this controller since that is what we will use for signup and login.

我们需要做的第一件事是将User工厂注入该控制器,因为这将用于注册和登录。

// authenticate.js
angular
  .module('app.authenticate', [])
  .controller('AuthenticateController', ['User', '$rootScope', '$state', AuthenticateController]);

function AuthenticateController(User, $rootScope, $state) {
  ...

$rootScope is also injected here so that we can bind the user to it after signing up or logging in. We are grabbing $state from ui-router as well so that we can redirect a user after successfully signing up or logging in. The next step is to create the signup and login functions:

$rootScope也注入到此处,以便我们在注册或登录后将用户与其绑定。我们也从ui-router抓取$state ,以便在成功注册或登录后可以重定向用户。步骤是创建signuplogin功能:

// authenticate.js
function AuthenticateController(User, $rootScope, $state) {
  var authenticate = this;

  // create the objects for our forms
  authenticate.signupData = {};
  authenticate.loginData  = {};

  // bind the functions to our controller
  authenticate.signup = signup;
  authenticate.login  = login;

  /**
   * Sign a user up and bind their info to $rootScope 
   */
  function signup() {
    User.signup(authenticate.signupData)
      .then(function(data) {
        if (data.get('_id')) {
          $rootScope.currentUser.id    = data.get('_id');
          $rootScope.currentUser.name  = data.get('displayName');
          $rootScope.currentUser.image = data.get('profileImg');

          // redirect the user
          $state.go('home');
        }
      });
  }

  /**
   * Use the User factory to log a user in
   * Bind the user's information to $rootScope
   */
  function login() {
    User.login(authenticate.loginData)
      .then(function(data) {
        if (data.get('_id')) {
          $rootScope.currentUser.id    = data.get('_id');
          $rootScope.currentUser.name  = data.get('displayName');
          $rootScope.currentUser.image = data.get('profileImg');

          // redirect the user
          $state.go('home');
        }
      });
  }
}

Now we have the functionality to sign a user up or log a user in! We are also

现在,我们具有注册用户或登录用户的功能! 我们也是

测试注册和登录 (Testing Signup and Login)

Let's check on all our work up to this point and test everything. Run a stamplay deploy and go visit your application in browser.

让我们检查到目前为止的所有工作并测试所有内容。 运行stamplay deploy ,然后在浏览器中访问您的应用程序。

Everything should be routing correctly and you should see your login and signup forms when you click Sign in or Register.

一切都应该正确路由,并且单击“ 登录”或“ 注册”时,您应该会看到登录和注册表单。

Let's try a user sign up and see if it works!

让我们尝试一个用户注册,看看是否有效!

09-angular-etsy-stamplay-test-user-signup

We have signed a user up and been redirected to the home page now! Let's go to the Stamplay dashboard and see our user in our database.

我们已经注册了一个用户,现在已重定向到主页! 让我们转到Stamplay仪表板,在数据库中查看我们的用户。

10-angular-etsy-stamplay-user-signed-up

Go ahead and test that you can logout and log back in also. We now have all of our authentication ready to go!

继续并测试您是否可以注销并重新登录。 现在,我们可以进行所有身份验证了!

The last thing we'll do in Part 2 is to allow users to create products and to show all products on the home page.

我们在第2部分中要做的最后一件事是允许用户创建产品并在主页上显示所有产品。

产品服务 (The Product Service)

Just like when we interacted with the Stamplay User API, we will need a service to interact with the API for products.

就像我们与Stamplay用户API进行交互时一样,我们需要一种服务来与产品的API进行交互。

Let's go ahead and create our ProductService now and we'll only need the basic CRUD functionality.

现在开始创建我们的ProductService ,我们只需要基本的CRUD功能。

The basics of the Stamplay JS SDK is that there are Models and Collections. Models are for grabbing on singular object and Collections are for multiple. We'll use each in the appropriate functions.

Stamplay JS SDK的基础是有ModelCollection 。 模型用于捕获单个对象,集合用于多个对象。 我们将在适当的函数中使用它们。

The functions we are going to have in the ProductService are:

我们将在ProductService中拥有的功能是:

  • all(): Grab all products

    all() :获取所有产品
  • get(id): Get a single product

    get(id) :获取单个产品
  • create(data): Create a product

    create(data) :创建产品
  • update(id, data): Update a specific product with new information

    update(id, data) :使用新信息更新特定产品
  • destroy(id): Delete a certain product

    destroy(id) :删除某个产品
  • getComments(id): Get the comments for a certain product

    getComments(id) :获取特定产品的评论
  • comment(id, data): Add a comment to a product

    comment(id, data) :向产品添加评论
  • getCategories(): Get all the categories so we can use them when we create products.

    getCategories() :获取所有类别,以便我们在创建产品时可以使用它们。

These are the six functions we are going to have on our Product. The CRUD stuff is pretty standard. We'll use a Stamplay Collection to grab all the products and a Stamplay Model when we work with a singular product.

这是我们要在产品上拥有的六个功能。 CRUD的东西很标准。 当我们使用单个产品时,我们将使用Stamplay集合来获取所有产品,并使用Stamplay模型。

The interesting thing to note here is that on all custom objects, Stamplay provides an actions object on each and every custom object. This means that we have three really useful attributes available:

这里要注意的有趣一点是,在所有自定义对象上,Stamplay在每个自定义对象上都提供了一个actions对象。 这意味着我们拥有三个非常有用的属性:

  • comments

    注释
  • ratings

    等级
  • votes

    票数

We can see if we go into the Stamplay Dashboard and view all products in the API Console, we have the actions object available to us.

我们可以查看是否进入Stamplay仪表板并在API控制台中查看所有产品,就可以使用actions对象。

11-angular-etsy-stamplay-show-special-fields

Be sure to look at the Stamplay JS SDK Docs for more information on what we can do with Models and Collections.

请务必查看Stamplay JS SDK文档 ,以获取有关我们可以对模型和集合执行的操作的更多信息。

Let's define our ProductService.js file now so we can start letting users create and see products.

现在定义我们的ProductService.js文件,以便我们开始让用户创建和查看产品。

// app.js
angular 
  .module('ProductService', [])
  .factory('Product', ['$stamplay', '$q', '$http', ProductService]);

function ProductService($stamplay, $q, $http) {

  return {
    all: all,
    get: get,
    create: create,
    update: update,
    destroy: destroy,
    getComments: getComments,
    comment: comment,
    createPicture: createPicture,
    getCategories: getCategories
  };

  /** 
   * Get all the products
   */
  function all() {
    var def = $q.defer();

    // instanticate a new product collection from the stamplay js sdk
    var products = new Stamplay.Cobject('products').Collection;
    products.populate().fetch()
      .then(function() {
        def.resolve(products);
      });

    return def.promise;
  }

  /**
   * Get a single product
   */
  function get(id) {
    var def = $q.defer();

    // instanticate a new product model from the stamplay js sdk
    var product = new Stamplay.Cobject('products').Model;

    // get the product in question and return it
    product.fetch(id)
      .then(function() {
        def.resolve(product);
      });

    return def.promise;
  }

  /**
   * Create a product
   */
  function create(data) {
    var def = $q.defer();

    // instanticate a new product model from the stamplay js sdk
    var product = new Stamplay.Cobject('products').Model;
    // loop over the fields in data and update the product
    angular.forEach(data, function(value, key) {
      product.set(key, value);
    });
    product.save()
      .then(function() {
        def.resolve(product);
      });

    return def.promise;
  }

  /**
   * Update an existing product
   */
  function update(id, data) {
    var def = $q.defer();

    // instanticate a new product model from the stamplay js sdk
    var product = new Stamplay.Cobject('products').Model;
    product.fetch(id)
      .then(function() {
        // loop over the fields in data and update the product
        angular.forEach(data, function(value, key) {
          product.set(key, value);
        });
        return product.save();
      })
      .then(function() {
        // return the product
        def.resolve(product);
      });

    return def.promise;
  }

  /**
   * DESTROY a product
   */
  function destroy(id) {
    var def = $q.defer();

    // instanticate a new product model from the stamplay js sdk
    var product = new Stamplay.Cobject('products').Model;
    product.fetch(id)
      .then(function() {
        return product.destroy();
      })
      .then(function() {
        // return true that the product was deleted
        def.resolve({ 'success': true });
      });

    return def.promise;
  }

  /**
   * Get all the comments for a specific product
   */
  function getComments(id) {
    var def = $q.defer();

    // instanticate a new product model from the stamplay js sdk
    var product = new Stamplay.Cobject('products').Model;
    product.fetch(id)
      .then(function() {
        // a user will comment on the found product
        def.resolve(product.getComments());
      });

    return def.promise;
  }

  /**
   * Comment on a product
   */
  function comment(id, data) {
    var def = $q.defer();

    // instanticate a new product model from the stamplay js sdk
    var product = new Stamplay.Cobject('products').Model;
    product.fetch(id)
      .then(function() {
        // a user will comment on the found product
        return product.comment(data.text);
      })
      .then(function() {
        // return the product
        def.resolve(product);
      });

    return def.promise;
  } 

  /**
   * Create a picture
   */
  function createPicture(files) {
    var def = $q.defer();

    // create an object for the ids
    var pictureIDs = [];

    // loop over the files and upload them via the Stamplay API
    angular.forEach(files, function(file) {

      // create a new formdata to store our image
      var fd = new FormData();
      fd.append('photo', file);

      // process the upload
      $http({
        method: 'POST',
        url: 'https://angularetsy.stamplayapp.com/api/cobject/v1/pictures',
        data: fd,
        headers: { 'Content-Type': undefined },
        photo: file
      })
        .then(function(response) {
          // push the given id into the pictureIDs array
          pictureIDs.push(response.data.id);
          def.resolve({ pictures: pictureIDs });
        });
    });

    return def.promise;
  }

  /**
   * Get all the product categories
   */
  function getCategories() {
      var def = $q.defer();

      // instanticate a new product collection from the stamplay js sdk
      var products = new Stamplay.Cobject('categories').Collection;
      products.populate().fetch()
          .then(function() {
              def.resolve(products);
          });

      return def.promise;
  }

}

申请我们的申请 (Applying to Our Application)

Next step is to add this ProductService to our app.js dependencies:

下一步是将此ProductService添加到我们的app.js依赖项中:

// app.js
angular
  .module('etsyApp', [
    ...
    'ProductService'
  ])

在主页上查看所有产品 (Viewing All Products on the Home Page)

Let's use this ProductService to grab all the products for viewing on the home page since our home page is pretty sparse right now.

由于我们的首页目前非常稀疏,因此让我们使用此ProductService来获取所有要在主页上查看的产品。

We're going to handle all this in the app/components/home/ directory. Open up app/components/home/home.js and we'll start here. First we need to inject the Product factory now that we have access to it:

我们将在app/components/home/目录中处理所有这些问题。 打开app/components/home/home.js ,我们将从这里开始。 首先,我们需要访问Product工厂,现在我们可以对其进行注入:

// home.js
angular
  .module('app.home', [])
  .controller('HomeController', ['Product', HomeController]);

function HomeController(Product) {
  var home = this;

  // get all the products here
}

The next step is to use the Product.all() call to grab all of our products.

下一步是使用Product.all()调用来获取我们所有的产品。

// home.js
function HomeController(Product) {
  var home = this;

  // get all the products and bind them to home.products
  Product.all()
    .then(function(data) {
      home.products = data.instance;
    });
}

With all the products bound to home.products, we can ng-repeat over them in our home.html file. That simple!

将所有产品绑定到home.products后,我们可以在home.html文件中对其进行ng-repeat 。 这么简单!

Let's go do that now in home.html:

让我们现在在home.html

<!-- home.html -->
<div class="page-header text-center">
  <h1>Top Products</h1>
</div>

<div class="row">

  <!-- loop over home.products here -->
  <div class="col-sm-4" ng-repeat="product in home.products">
    <div class="product-box">

      <!-- the product image -->
      <a class="product-img" ui-sref="product({ id: product.instance.id, name: product.instance.name })">
        <img ng-src="{{ product.instance.pictures[0].photo }}" ng-show="product.instance.pictures">
        <img src="http://placebear.com/g/250/170" ng-show="!product.instance.pictures">
      </a>

      <!-- the product content like title -->
      <div class="product-content">
        <a ui-sref="product({ id: product.instance.id, name: product.instance.name })">
          {{ product.instance.name }}
        </a>
        <div class="listing-price">
          {{ product.instance.price | currency }}
        </div>
      </div>
    </div>  
  </div>

</div>

That is all we need to loop over the products that Stamplay gives us back from the API. Right now it's pretty sparse since the demo product we created in Part 1 only had a name (no price, colors, sizes, pictures, category), but we'll fix that soon by letting users create their own products.

这就是我们需要遍历Stamplay从API返回的产品的全部。 现在,由于我们在第1部分中创建的演示产品仅具有名称(没有价格,颜色,大小,图片,类别),因此它非常稀疏,但是我们将通过允许用户创建自己的产品来尽快解决该问题。

We're attaching ui-srefs to the image and to the title so users can click through to see the product. ui-router will then route us to the appropriate page. We are passing the parameters into ui-sref as an object also. Read more about that on our ui-router tips article.

我们在图像和标题上附加了ui-sref ,以便用户可以单击以查看产品。 ui-router然后将我们路由到适当的页面。 我们也将参数作为对象传递给ui-sref 。 在我们的ui-router技巧文章中阅读有关此内容的更多信息。

We're going to be showing the product picture if it exists (we're checking with ng-show) and if there is no product picture, then we'll just use a picture of a majestic bear.

我们将显示产品图片是否存在(我们正在使用ng-show检查),如果没有产品图片,那么我们将仅使用雄伟的熊的图片。

12-angular-etsy-stamplay-repeating-products

添加一些样式 (Adding Some Styling)

Here is some styling to match our products to Etsy stylings:

以下是一些样式,可将我们的产品与Etsy样式匹配:

// style.css
/* products ------------------------------------ */
.product-box  {
  background:#FFF;
  border-color:#CACACA;
  border-bottom-color:#DADADA;
  box-shadow:0 0 2px 0 rgba(0, 0, 0, 0.15);
  border-radius:3px;
  padding:8px;
}

.product-img img {
  display:block;
  margin:0 auto 10px;
  max-width:100%;
}

.product-content a  {
  text-align:center;
  font-size:14px;
  color:#696969;
  display:block;
}

.product-content .listing-price {
  text-align:right;
  color:#78C042;
  font-size:12px;
}

Alright now we're getting closer to an Etsy look!

好了,现在我们正接近Etsy外观!

13-angular-etsy-stamplay-home-styled

显示单个产品 (Showing a Single Product)

We've wired up the img and the product title to link to the product page. This is where we'll show off the product.

我们已将img和产品标题连接起来,以链接到产品页面。 这是我们展示产品的地方。

Note: ui-router by default will urlencode your URLs when using ui-sref. To get rid of this behavior, follow the instructions outlined on this stack overflow answer.

注意:默认情况下,ui-router会在使用ui-sref时对您的URL进行URL编码。 要摆脱这种现象,请遵循此堆栈溢出答案中概述的说明。

We're going to follow the same steps as before to connect with the Stamplay API through our Angular service and then show that in our view.

我们将按照与以前相同的步骤通过Angular服务与Stamplay API连接,然后在我们的视图中进行显示。

All of the following work will be done in app/components/product/. Let's open up app/components/product/product.js and use the Product factory to grab the single product based on the name in the URL route.

以下所有工作将在app/components/product/ 。 让我们打开app/components/product/product.js并使用Product工厂根据URL路径中的名称获取单个产品。

// product.js
angular
  .module('app.product', [])
  .controller('ProductController', ['Product', '$stateParams', ProductController]);

function ProductController(Product, $stateParams) {
  var product = this;

  // get the product for this page and bind it to the product.listing object
  Product.get($stateParams.id)
    .then(function(data) {
      // since this is a singular Stamplay model that was returned, we can bind instance directly
      product.listing = data.instance;
    });
}

We are using the Product.get(id) function that we created earlier. $stateParams, provided by ui-router will allow us to grab the url parameters. In this case, we need the id.

我们正在使用之前创建的Product.get(id)函数。 ui-router提供的$stateParams将允许我们获取url参数。 在这种情况下,我们需要id

The Stamplay API and SDK will return a single instance since we are only looking for one product. With this, we will bind it to the controller as the listing object.

Stamplay API和SDK将返回一个实例,因为我们只在寻找一种产品。 这样,我们会将其作为listing对象绑定到控制器。

Now that we've grabbed this product, we can display it in our view, app/components/product/product.html.

现在,我们已经掌握了该产品,可以在视图中将其显示在app/components/product/product.html

This is going to be a lot of code, but we're just laying out the entire product page. There are the images, comments, and content to show so just bear with us.

这将是很多代码,但是我们只是布局整个产品页面。 有图片,评论和内容要显示,所以请耐心等待。

<!-- product.html -->
<div class="listing-wrap">
  <div class="row">

    <!-- main content (images, description, comments) -->
    <div class="col-sm-7">
    <div class="listing-main">

      <!-- the images (show the bears if there are no images -->
      <div class="listing-images">
        <img 
            ng-repeat="picture in product.pictures" 
            ng-show="picture.photo"
            ng-src="{{ picture.photo }}"
            class="img-responsive">
        <img 
            ng-show="!product.listing.pictures"
            src="http://placebear.com/g/600/400" 
            class="img-responsive">
      </div>

      <!-- the description -->
      <div class="listing-description">
        <h3>Description</h3>
        {{ product.listing.description }}
      </div>

      <!-- the comments (ng-repeat over the comments) -->
      <h3>Comments</h3>
      <div class="listing-comments">
        <div class="comment" ng-repeat="comment in product.listing.actions.comments">
          {{ comment.text }}
        </div>
      </div>

    </div>
    </div>

    <!-- the extra content (title, price, options, add to cart) -->
    <div class="col-sm-5">
    <div class="listing-extra">

      <!-- the extras info -->
      <div class="listing-info">
        <h1>{{ product.listing.name }}</h1>

        <!-- the price -->
        <div class="listing-price">
          {{ product.listing.price | currency }}
        </div>

        <!-- loop over the colors -->
        <ul class="listing-colors">
          <li ng-repeat="color in product.listing.color">{{ color }}</li>
        </ul>

        <!-- loop over the sizes -->
        <ul class="listing-sizes">
          <li ng-repeat="size in product.listing.size">{{ size }}</li>
        </ul>
      </div>

      <!-- buy now button links to checkout route -->
      <a ui-sref="checkout({ id: product.listing.id })" class="listing-buy btn btn-success btn-block">
        Buy Now
      </a>

    </div>
    </div>

  </div>
</div>

Now to add a bit of styling to style.css:

现在向style.css添加一些样式:

/* style.css */
/* listing ------------------------------------- */
.listing-wrap       {
  background:#FFF;
  border:1px solid #ECECEC;
  border-radius:3px;
  padding:30px;
}

.listing-images img   {
  border-radius:3px;
  margin-bottom:20px;
}

.listing-description {
  font-size:16px;
  margin-bottom:20px;
}

.listing-comments   {
  background:#FEFEFE;
  border-radius:3px;
  padding:20px;
}

.listing-comments .comment  {
  margin-bottom:15px;
}

.listing-extra    {
  border:10px solid #E4F3D9;
  border-radius:3px;
  padding:20px;
}

.listing-extra h1 {
  font-size:20px;
  line-height:1.2;
  color:#333;
  margin:0 0 15px;
}

Now this page is a little scarce too since our demo product didnt' have all the much information.

现在,由于我们的演示产品没有太多的信息,因此该页面也有点稀缺。

14-angular-etsy-stamplay-product-page

Let's move onto creating products now so we can get the full experience of our product pages. The last thing we'll do here is handle the form for letting logged in users create products.

现在让我们继续创建产品,以便获得产品页面的完整体验。 我们在这里要做的最后一件事是处理允许登录用户创建产品的表单。

Before we can create a product, we'll need to create some categories for our products. Let's log into the Stamplay dashboard and create those real quick.

在创建产品之前,我们需要为我们的产品创建一些类别。 让我们登录Stamplay仪表板并快速创建它们。

创建类别 (Creating Categories)

In the API Console, select Create object and select categories in the dropdown. We'll have product category types universal across our entire site and we'll generate them here.

在API控制台中,选择“ 创建对象”,然后在下拉列表中选择类别 。 我们将在整个网站上提供通用的产品类别类型,并在此处生成它们。

Let's create five different categories.

让我们创建五个不同的类别。

  • Shirts

    上衣
  • Shorts

    短裤
  • Electronics

    电子产品
  • Woodwork

    木制品
  • Handcrafted

    手工制作

Now if we Get all object, we should be able to see our categories in the API Console.

现在,如果我们获取所有对象 ,则应该可以在API控制台中看到我们的类别。

Let's move onto creating a new product now.

现在让我们继续创建新产品。

创造新产品 (Creating a New Product)

We'll lump a lot of admin type functionality into the admin component. The first feature we'll add into the admin component is to create a product.

我们将大量的管理类型功能集成到admin组件中。 我们将添加到admin组件中的第一个功能是创建产品。

As

翻译自: https://scotch.io/tutorials/build-an-etsy-clone-with-angular-and-stamplay-part-2

angular 克隆

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值