本文共 51893 字,大约阅读时间需要 172 分钟。
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发挥重要作用的地方。 本章的结尾如下所示:
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的。
Here are the steps that we'll follow along with:
以下是我们将遵循的步骤:
Note: You need installed to have npm available to you.
注意:您需要安装才能使用npm。
npm install -g stamplay-cli
安装Stamplay CLI工具: npm install -g stamplay-cli
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>上看到它。
Let's initialize our Stamplay project with the following commands:
让我们使用以下命令初始化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 ID和Api密钥 。 请记住,由于Api密钥具有类似神的功能(创建,更新和删除内容的完全访问权限),因此应将其保密。
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仪表板中找到:
Now we can try to deploy our application using:
现在,我们可以尝试使用以下方法部署应用程序:
$ 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应用程序奠定基础。
Our Angular app will be very straightforward. We'll use for routing and have the following pages:
我们的Angular应用程序将非常简单。 我们将使用进行路由,并具有以下页面:
With those pages in mind, let's get started.
考虑到这些页面,让我们开始吧。
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服务。
We're going to use to grab the front-end resources we need. To install Bower, run the following:
我们将使用来获取所需的前端资源。 要安装Bower,请运行以下命令:
$ npm install -g bower
For more info on Bower, read our . Now that we have bower installed, we just need to create a bower.json
file by using the following command:
有关Bower的更多信息,请阅读我们的 。 现在我们已经安装了bower,我们只需要使用以下命令来创建bower.json
文件:
$ bower init
Just use the defaults here and then we can finally install our dependencies that we need. We will be using the following:
只需在此处使用默认值,我们就可以最终安装所需的依赖项。 我们将使用以下内容:
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:
相关阅读:
With all that ready to go, let's create our index.html
file which will be the base for our entire application.
准备就绪后,让我们创建index.html
文件,它将作为整个应用程序的基础。
Let's create all those files now and take a look at our index.html
file.
现在让我们创建所有这些文件,并查看我们的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.js
和style.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.
我们还将用header , footer和Angular和ui-router注入我们的视图的主要部分来布局整个应用程序。
Here is the start of our index.html
file:
这是我们的index.html
文件的开始:
Angular Etsy Stamplay
Let's go piece by piece and fill in the blanks.
让我们一步一步去填补空白。
We're loading the Cerulean Bootswatch theme and our own style.css
file that we created earlier.
我们正在加载Cerulean Bootswatch主题和我们先前创建的我们自己的style.css
文件。
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 or to minify and combine/concatenate all these files together into one singular file.
起初这似乎是最艰巨的。 但是,我们将逐步解决它。 记住,在生产级应用程序中,您想使用任务运行程序(例如或来将所有这些文件最小化并将其组合/合并为一个单一文件。
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>
。
We're going to need a <header>
, <main>
, and <footer>
so let's create those:
我们将需要一个<header>
, <main>
和<footer>
因此让我们创建它们:
Most of this is stylings and we'll be filling in the link hrefs
(or ui-sref
s in our case since we're using ) once we have our Angular routes configured.
其中大多数是 hrefs
一旦配置了Angular路由,我们将填写链接hrefs
(或本例中的ui-sref
,因为我们使用的是 )。
We'll also be using those logged in links if a user is not logged in via Stamplay.
如果用户未通过Stamplay登录,我们还将使用那些已登录的链接。
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;}
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 .
然后可以在查看我的应用程序。
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 ! If you want to share it with people, feel free. It doesn't do much yet but it will very soon.
继续进行stamplay deploy
,我们还可以在实时查看我们的应用程序! 如果您想与人分享,请放心。 它并没有做很多,但很快就会完成。
图片
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 so if you need a primer on that, be sure to read our article.
我们的应用程序还没有真正做很多事情,但是让我们开始在Angular方面进行工作,以获得我们想要的所有功能。 我们将使用因此,如果您需要使用 ,请务必阅读我们的《 》。
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
文件。
Here we will create our angular.module
and create a MainController
to encompass our entire application.
在这里,我们将创建angular.module
并创建一个MainController
来包含整个应用程序。
// app.jsangular .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
并注入了ngStamplay
, ui.router
和app.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>
标记上执行此操作:
......
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
模块而抛出错误。
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.jsangular .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.
感觉确实很不错,因为它是我们到目前为止制作的最长的文件,但是非常简单。
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:
注意:如果您想知道为什么要这样定义.config()
,它是为了缩小目的。 阅读更多:
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>
标记,因此它们不会做任何事情。
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>
部分)。
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
来处理。 我们将在几节中介绍登录功能后再进行处理。
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控制器。 让我们为每个文件执行此操作。 只需将以下内容放入每个文件即可。 这将是每个的基本模板。
// home.jsangular .module('app.home', []) .controller('HomeController', HomeController);function HomeController() { var home = this;}
// admin.jsangular .module('app.admin', []) .controller('AdminController', AdminController);function AdminController() { var admin = this;}
// authenticate.jsangular .module('app.authenticate', []) .controller('AuthenticateController', AuthenticateController);function AuthenticateController() { var authenticate = this;}
// checkout.jsangular .module('app.checkout', []) .controller('CheckoutController', CheckoutController);function CheckoutController() { var checkout = this;}
// product.jsangular .module('app.product', []) .controller('ProductController', ProductController);function ProductController() { var product = this;}
// profile.jsangular .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现在将知道为某个视图拉入哪个。 我们要做的就是现在将它们注入到我们的主应用程序中。
Go into the app.js
file and inject the following into the dependencies:
进入app.js
文件,并将以下内容注入依赖项:
// app.jsangular .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的变化。
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后端进行对话。
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模块已为我们提供了许多功能。
The main functions in our UserService will be:
我们的UserService的主要功能将是:
Here is the app/shared/UserService.js
file:
这是app/shared/UserService.js
文件:
// UserService.jsangular .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.
这里有四个主要功能: getCurrent
, signup
, login
和logout
。 这些格式非常相似。 我们将使用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
功能,我们只需要传递email
, password
和displayName
创建该用户。 然后,我们将在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.jsangular .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
工厂。
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.jsfunction 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 to see how you can add your local domain to your application and have the ability to test locally.
注意:如果要在本地测试应用程序,则会看到运行User.getCurrent()
出错。 这是因为Stamplays CORS安全性仅允许来自指定域的访问。 查看以了解如何将本地域添加到应用程序中并具有在本地进行测试的能力。
Let's hide all the things that require a login in our index.html
file.
让我们在index.html
文件中隐藏所有需要登录的内容。
We will use on our <ul>
tags.
我们将在<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
),我们将显示已登录的链接,如果不存在则显示已注销的链接。
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.jsfunction 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
的“ 注销”按钮中:
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
页面,用户可以在其中使用其电子邮件地址进行注册。
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
组件中,并让人们在此处登录和注册。
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
文件中,我们将为登录/注册页面创建视图。 我们将页面分为两半,左侧为注册,右侧为登录。
Here is the code in app/components/authenticate/authenticate.html
:
这是app/components/authenticate/authenticate.html
的代码:
Sign Up
Login
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上的特定对象( signupData
和loginData
)。
Let's move forward and create the controller that will handle submitting both of these forms.
让我们继续前进,创建一个控制器来处理这两种形式的提交。
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.jsangular .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
,以便在成功注册或登录后可以重定向用户。步骤是创建signup
和login
功能:
// authenticate.jsfunction 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
现在,我们具有注册用户或登录用户的功能! 我们也是
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!
让我们尝试一个用户注册,看看是否有效!
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仪表板,在数据库中查看我们的用户。
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部分中要做的最后一件事是允许用户创建产品并在主页上显示所有产品。
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 Model
s and Collection
s. Models are for grabbing on singular object and Collections are for multiple. We'll use each in the appropriate functions.
Stamplay JS SDK的基础是有Model
和Collection
。 模型用于捕获单个对象,集合用于多个对象。 我们将在适当的函数中使用它们。
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
对象。 这意味着我们拥有三个非常有用的属性:
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
对象。
Be sure to look at the for more information on what we can do with Models and Collections.
请务必查看 ,以获取有关我们可以对模型和集合执行的操作的更多信息。
Let's define our ProductService.js
file now so we can start letting users create and see products.
现在定义我们的ProductService.js
文件,以便我们开始让用户创建和查看产品。
// app.jsangular .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; }}
Next step is to add this ProductService
to our app.js
dependencies:
下一步是将此ProductService
添加到我们的app.js
依赖项中:
// app.jsangular .module('etsyApp', [ ... 'ProductService' ])
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.jsangular .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.jsfunction 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
:
Top Products
{ { product.instance.name }}{ { product.instance.price | currency }}
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-sref
s 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 article.
我们在图像和标题上附加了ui-sref
,以便用户可以单击以查看产品。 ui-router然后将我们路由到适当的页面。 我们也将参数作为对象传递给ui-sref
。 在我们的文章中阅读有关此内容的更多信息。
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
检查),如果没有产品图片,那么我们将仅使用雄伟的熊的图片。
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外观!
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 .
注意:默认情况下,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.jsangular .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.
这将是很多代码,但是我们只是布局整个产品页面。 有图片,评论和内容要显示,所以请耐心等待。
Description
{ { product.listing.description }}Comments
{ { comment.text }}Buy Now{ { product.listing.name }}
{ { product.listing.price | currency }}
- { { color }}
- { { size }}
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.
现在,由于我们的演示产品没有太多的信息,因此该页面也有点稀缺。
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仪表板并快速创建它们。
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.
让我们创建五个不同的类别。
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.
现在让我们继续创建新产品。
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
如
翻译自:
angular 克隆
转载地址:http://sjywd.baihongyu.com/