diff --git a/aio/content/start/start-routing.en.md b/aio/content/start/start-routing.en.md new file mode 100644 index 0000000000..3a5a3cf196 --- /dev/null +++ b/aio/content/start/start-routing.en.md @@ -0,0 +1,375 @@ +# Try it: Manage data + +At the end of [In-app Navigation](start/start-routing "Try it: In-app Navigation"), the online store application has a product catalog with two views: a product list and product details. +Users can click on a product name from the list to see details in a new view, with a distinct URL, or route. + +This page guides you through creating the shopping cart in three phases: + +* Update the product details view to include a "Buy" button, which adds the current product to a list of products that a cart service manages. +* Add a cart component, which displays the items in the cart. +* Add a shipping component, which retrieves shipping prices for the items in the cart by using Angular's `HttpClient` to retrieve shipping data from a `.json` file. + +{@a services} +## Services + +Services are an integral part of Angular applications. In Angular, a service is an instance of a class that you can make available to any part of your application using Angular's [dependency injection system](guide/glossary#dependency-injection "Dependency injection definition"). + +Services are the place where you share data between parts of your application. For the online store, the cart service is where you store your cart data and methods. + +{@a create-cart-service} +## Create the shopping cart service + +Up to this point, users can view product information, and +simulate sharing and being notified about product changes. +They cannot, however, buy products. + +In this section, you add a "Buy" button to the product +details view and set up a cart service to store information +about products in the cart. + +
+ +A later part of this tutorial, [Use forms for user input](start/start-forms "Try it: Forms for user input"), guides you through accessing this cart service from the view where the user checks out. + +
+ +{@a generate-cart-service} +### Define a cart service + +1. To generate a cart service, right click on the `app` folder, choose `Angular Generator`, and choose `Service`. Name the new service `cart`. + + + +
Intro to Services and DI"). + +
+ +1. In the `CartService` class, define an `items` property to store the array of the current products in the cart. + + + +1. Define methods to add items to the cart, return cart items, and clear the cart items: + + + + * The `addToCart()` method appends a product to an array of `items`. + + * The `getItems()` method collects the items users add to the cart and returns each item with its associated quantity. + + * The `clearCart()` method returns an empty array of items. + +{@a product-details-use-cart-service} +### Use the cart service + +This section walks you through using the cart service to add a product to the cart with a "Buy" button. + +1. Open `product-details.component.ts`. + +1. Configure the component to use the cart service. + + 1. Import the cart service. + + + + + 1. Inject the cart service by adding it to the `constructor()`. + + + + + + +1. Define the `addToCart()` method, which adds the current product to the cart. + + The `addToCart()` method does the following three things: + * Receives the current `product`. + * Uses the cart service's `addToCart()` method to add the product the cart. + * Displays a message that you've added a product to the cart. + + + +1. Update the product details template with a "Buy" button that adds the current product to the cart. + + 1. Open `product-details.component.html`. + + 1. Add a button with the label "Buy", and bind the `click()` event to the `addToCart()` method: + + + + +
+ + The line, `

{{ product.price | currency }}

` uses the `currency` pipe to transform `product.price` from a number to a currency string. A pipe is a way you can transform data in your HTML template. For more information about Angular pipes, see [Pipes](guide/pipes "Pipes"). + +
+ +1. To see the new "Buy" button, refresh the application and click on a product's name to display its details. + + + + 1. Click the "Buy" button to add the product to the stored list of items in the cart and display a confirmation message. + + + + +## Create the cart view + +At this point, users can put items in the cart by clicking "Buy", but they can't yet see their cart. + +Create the cart view in two steps: + +1. Create a cart component and configure routing to the new component. At this point, the cart view has only default text. +1. Display the cart items. + +### Set up the component + + To create the cart view, begin by following the same steps you did to create the product details component and configure routing for the new component. + +1. Generate a cart component, named `cart`. + + Reminder: In the file list, right-click the `app` folder, choose `Angular Generator` and `Component`. + + + +1. Add routing (a URL pattern) for the cart component. + + Open `app.module.ts` and add a route for the component `CartComponent`, with a `path` of `cart`: + + + + +1. Update the "Checkout" button so that it routes to the `/cart` url. + + Open `top-bar.component.html` and add a `routerLink` directive pointing to `/cart`. + + + + +1. To see the new cart component, click the "Checkout" button. You can see the "cart works!" default text, and the URL has the pattern `https://getting-started.stackblitz.io/cart`, where `getting-started.stackblitz.io` may be different for your StackBlitz project. + + + +### Display the cart items + +You can use services to share data across components: + +* The product details component already uses the cart service to add products to the cart. +* This section shows you how to use the cart service to display the products in the cart. + + +1. Open `cart.component.ts`. + +1. Configure the component to use the cart service. + + 1. Import the `CartService` from the `cart.service.ts` file. + + + + + 1. Inject the `CartService` so that the cart component can use it. + + + + +1. Define the `items` property to store the products in the cart. + + + + +1. Set the items using the cart service's `getItems()` method. Recall that you defined this method [when you generated `cart.service.ts`](#generate-cart-service). + + The resulting `CartComponent` class is as follows: + + + + +1. Update the template with a header, and use a `
` with an `*ngFor` to display each of the cart items with its name and price. + + The resulting `CartComponent` template is as follows: + + + + +1. Test your cart component. + + 1. Click on "My Store" to go to the product list view. + 1. Click on a product name to display its details. + 1. Click "Buy" to add the product to the cart. + 1. Click "Checkout" to see the cart. + 1. To add another product, click "My Store" to return to the product list. + + Repeat to add more items to the cart. + + + + +
+ +StackBlitz tip: Any time the preview refreshes, the cart is cleared. If you make changes to the app, the page refreshes, so you'll need to buy products again to populate the cart. + +
+ +
+ +For more information about services, see [Introduction to Services and Dependency Injection](guide/architecture-services "Concepts > Intro to Services and DI"). + +
+ + +## Retrieve shipping prices + + +Servers often return data in the form of a stream. +Streams are useful because they make it easy to transform the returned data and make modifications to the way you request that data. +The Angular HTTP client, `HttpClient`, is a built-in way to fetch data from external APIs and provide them to your app as a stream. + +This section shows you how to use the HTTP client to retrieve shipping prices from an external file. + +### Predefined shipping data + +The application that StackBlitz generates for this guide comes with predefined shipping data in `assets/shipping.json`. +Use this data to add shipping prices for items in the cart. + + + + + +### Use `HttpClient` in the `AppModule` + +Before you can use Angular's HTTP client, you must configure your app to use `HttpClientModule`. + +Angular's `HttpClientModule` registers the providers your app needs to use a single instance of the `HttpClient` service throughout your app. + +1. Open `app.module.ts`. + + This file contains imports and functionality that is available to the entire app. + +1. Import `HttpClientModule` from the `@angular/common/http` package at the top of the file with the other imports. As there are a number of other imports, this code snippet omits them for brevity. Be sure to leave the existing imports in place. + + + + +1. Add `HttpClientModule` to the `AppModule` `@NgModule()` `imports` array to register Angular's `HttpClient` providers globally. + + + + +### Use `HttpClient` in the cart service + +Now that the `AppModule` imports the `HttpClientModule`, the next step is to inject the `HttpClient` service into your service so your app can fetch data and interact with external APIs and resources. + + +1. Open `cart.service.ts`. + +1. Import `HttpClient` from the `@angular/common/http` package. + + + + +1. Inject `HttpClient` into the `CartService` constructor: + + + + + +### Define the `get()` method + +Multiple components can leverage the same service. +Later in this tutorial, the shipping component uses the cart service to retrieve shipping data via HTTP from the `shipping.json` file. +First, define a `get()` method. + +1. Continue working in `cart.service.ts`. + +1. Below the `clearCart()` method, define a new `getShippingPrices()` method that uses the `HttpClient` `get()` method to retrieve the shipping data. + + + + +
+ +For more information about Angular's `HttpClient`, see the [Client-Server Interaction](guide/http "Server interaction through HTTP") guide. + +
+ +## Define the shipping view + +Now that your app can retrieve shipping data, create a shipping component and template. + +1. Generate a new component named `shipping`. + + Reminder: In the file list, right-click the `app` folder, choose `Angular Generator` and `Component`. + + + +1. In `app.module.ts`, add a route for shipping. Specify a `path` of `shipping` and a component of `ShippingComponent`. + + + + There's no link to the new shipping component yet, but you can see its template in the preview pane by entering the URL its route specifies. The URL has the pattern: `https://getting-started.stackblitz.io/shipping` where the `getting-started.stackblitz.io` part may be different for your StackBlitz project. + +1. Modify the shipping component so that it uses the cart service to retrieve shipping data via HTTP from the `shipping.json` file. + + 1. Import the cart service. + + + + 1. Define a `shippingCosts` property. + + + + 1. Inject the cart service in the `ShippingComponent` constructor: + + + + 1. Set the `shippingCosts` property using the `getShippingPrices()` method from the cart service. + + + +1. Update the shipping component's template to display the shipping types and prices using the `async` pipe: + + + + The `async` pipe returns the latest value from a stream of data and continues to do so for the life of a given component. When Angular destroys that component, the `async` pipe automatically stops. For detailed information about the `async` pipe, see the [AsyncPipe API documentation](/api/common/AsyncPipe). + +1. Add a link from the cart view to the shipping view: + + + +1. Test your shipping prices feature: + + Click the "Checkout" button to see the updated cart. Remember that changing the app causes the preview to refresh, which empties the cart. + + + + Click on the link to navigate to the shipping prices. + + + + +## Next steps + +Congratulations! You have an online store application with a product catalog and shopping cart. You can also look up and display shipping prices. + +To continue exploring Angular, choose either of the following options: +* [Continue to the "Forms" section](start/start-forms "Try it: Forms for User Input") to finish the app by adding the shopping cart view and a checkout form. +* [Skip ahead to the "Deployment" section](start/start-deployment "Try it: Deployment") to move to local development, or deploy your app to Firebase or your own server. diff --git a/aio/content/start/start-routing.md b/aio/content/start/start-routing.md index 42a4ce2ae0..57a9195f4c 100644 --- a/aio/content/start/start-routing.md +++ b/aio/content/start/start-routing.md @@ -1,113 +1,106 @@ -# In-app navigation +# Navegación en la aplicación -At the end of [part 1](start "Get started with a basic Angular app"), the online store application has a basic product catalog. -The app doesn't have any variable states or navigation. -There is one URL, and that URL always displays the "My Store" page with a list of products and their descriptions. +Al final de la [parte 1] (start "Empieza con una aplicación Angular básica"), la aplicación de la tienda en línea tiene un catálogo básico de productos. La aplicación no tiene ningun estado de variable o navegación. Hay una URL, y esa URL siempre muestra la pagina "Mi Tienda" con una lista de productos y sus descripciones. -This guide shows you how to use Angular [routing](guide/glossary#router "Router definition") to give the user in-app navigation. In a single-page app, instead of loading new pages, you show different components and data to the user based on where the user is in the application. +Esta guía te muestra cómo usar Angular [Routing](guide/glossary#router "Definición de Router") para brindarle al usuario navegación dentro de la aplicación. En una aplicación de una sola página, en lugar de cargar nuevas páginas, muestras diferentes componentes y datos al usuario en función de dónde se encuentra el usuario en la aplicación. -The router lets you display full product details in separate [views](guide/glossary#view "View definition"), each with its own URL. Routing enables navigation from one view to the next (within the same page) as users perform tasks such as the following: +El router te permite mostrar los detalles completos del producto en [vistas](guide/glossary#view "Definición de vista") separadas, cada una con su propia URL. El router habilita la navegación de una vista a la siguiente (dentro de la misma página) cuando los usuarios realizan tareas como las siguientes: -* Entering a URL in the address bar to navigate to a corresponding view. -* Clicking links on the page to navigate to a new view. -* Clicking the browser's back and forward buttons to navigate backward and forward through the browser history. +* Ingresando una URL en la barra de direcciones para navegar a la vista correspondiente. +* Haciendo clic en los enlaces de la página para navegar a una nueva vista. +* Haciendo clic en los botones de adelante y atrás del navegador para navegar hacia atrás y hacia adelante a través del historial del navegador. -## Registering a route +## Registro de una ruta -The app is already set up to use the Angular `Router` and to use routing to navigate to the product list component you modified earlier. This section shows you how to define a route to show individual product details. +La aplicación ya esta configurada para usar el Angular `Router` y usar el Routing para navegar al componente de la lista de productos que modificaste anteriormente. Esta sección te muestra cómo definir una ruta para mostrar los detalles de productos individualmente. -1. Generate a new component for product details. Give the component the name `product-details`. +1. Genera un nuevo componente para los detalles del producto. Asigna al componente el nombre `product-details`. - Reminder: In the file list, right-click the `app` folder, choose `Angular Generator` and `Component`. - -1. In `app.module.ts`, add a route for product details, with a `path` of `products/:productId` and `ProductDetailsComponent` for the `component`. + Recuerda: En la lista de archivos, haz clic con el botón derecho en la carpeta `app`, selecciona `Angular Generator` y `Component`. + +2. En `app.module.ts`, agrega una ruta para los detalles del producto, con un `path` de `products/:productId` y `ProductDetailsComponent` para el `component`. + + Una ruta asocia una o más URL con un componente. + +3. La directiva configura la plantilla del componente para definir cómo el usuario navega a la ruta o URL. Cuando el usuario hace clic en el nombre de un producto, la aplicación muestra los detalles de ese producto. - A route associates one or more URL paths with a component. + 1. Abre `product-list.component.html`. -1. The directive configures the component template to define how the user navigates to the route or URL. When the user clicks a product name, the app displays the details for that product. - - 1. Open `product-list.component.html`. - - 1. Update the `*ngFor` directive to assign each index in the `products` array to the `productId` variable when iterating over the list. - - 1. Modify the product name anchor to include a `routerLink`. + 1. Actualiza la directiva `*ngFor` para asignar cada índice en la matriz `products` a la variable `productId` cuando se itera sobre la lista. + 1. Modifica el ancla del nombre del producto para incluir un `routerLink`. + + + La directiva RouterLink le da al Router el control sobre el elemento de anclaje. En este caso, la ruta, o URL, contiene un segmento fijo, `/products`, mientras que el segmento final es variable, insertando la propiedad id del producto actual. Por ejemplo, la URL de un producto con un `id` de 1 será similar a `https://getting-started-myfork.stackblitz.io/products/1`. + +4. Prueba el Router haciendo clic en el nombre de un producto. La aplicación muestra el componente de detalles del producto, que actualmente siempre dice "product-details works!" - The RouterLink directive gives the router control over the anchor element. In this case, the route, or URL, contains one fixed segment, `/products`, while the final segment is variable, inserting the id property of the current product. For example, the URL for a product with an `id` of 1 will be similar to `https://getting-started-myfork.stackblitz.io/products/1`. - -1. Test the router by clicking a product name. The app displays the product details component, which currently always says "product-details works!" - - Notice that the URL in the preview window changes. The final segment is `products/#` where `#` is the number of the route you clicked. + Observa que cambia la URL en la ventana de vista previa. El segmento final es "products/#" donde "#" es el número de la ruta en la que hizo clic. + +## Utilizar información de la ruta +El componente de detalles del producto maneja la visualización de cada producto. El Angular Router muestra los componentes basados en la URL del navegador y sus rutas definidas. Esta sección te muestra cómo usar el Angular Router para combinar los datos de los `productos` y la información de la ruta para mostrar los detalles específicos de cada producto. +1. Abre `product-details.component.ts` -## Using route information - -The product details component handles the display of each product. The Angular Router displays components based on the browser's URL and your defined routes. This section shows you how to use the Angular Router to combine the `products` data and route information to display the specific details for each product. - -1. Open `product-details.component.ts` - -1. Arrange to use product data from an external file. - - 1. Import `ActivatedRoute` from the `@angular/router` package, and the `products` array from `../products`. +2. Organiza el uso de datos de productos desde un archivo externo. + 1. Importa `ActivatedRoute` del paquete `@angular/router` y la matriz `products` de `../products`. + - 1. Define the `product` property and inject the `ActivatedRoute` into the constructor by adding it as an argument within the constructor's parentheses. - + 1. Define la propiedad `product` e inyecta el `ActivatedRoute` en el constructor agregándolo como un argumento dentro de los paréntesis del constructor. + + + El `ActivatedRoute` es específico para cada componente enrutado que carga el Angular Router. Contiene información sobre la + ruta, sus parámetros y datos adicionales asociados con la ruta. - The `ActivatedRoute` is specific to each routed component that the Angular Router loads. It contains information about the - route, its parameters, and additional data associated with the route. - - By injecting the `ActivatedRoute`, you are configuring the component to use a *service*. The [Managing Data](start/start-data "Try it: Managing Data") page covers services in more detail. - - -1. In the `ngOnInit()` method, subscribe to route parameters and fetch the product based on the `productId`. + Inyectando el `ActivatedRoute`, estás configurando el componente para usar un *servicio*. La página [Manejo de Datos] (start/start-data "Pruébalo: Manejo de Datos") cubre los servicios con más detalle. + + +3. En el método `ngOnInit()`, suscríbete a los parámetros de ruta y obtén el producto basándote en el `productId`. - - The route parameters correspond to the path variables you define in the route. The URL that matches the route provides the `productId`. Angular uses the `productId` to display the details for each unique product. - -1. Update the template to display product details information inside an `*ngIf`. + + Los parámetros de la ruta corresponden a las variables de ruta (path) que se define en la ruta. La URL que coincide con la ruta proporciona el `productId`. Angular usa el `productId` para mostrar los detalles de cada producto único. + +4. Actualiza la plantilla para mostrar la información de detalle del producto dentro de un `*ngIf`. -Now, when users click on a name in the product list, the router navigates them to the distinct URL for the product, swaps out the product list component for the product details component, and displays the product details. +Ahora, cuando los usuarios hacen clic en un nombre en la lista de productos, el router los dirige a la URL distinta del producto, cambia el componente de la lista de productos por el componente de detalles del producto y muestra los detalles del producto. - -
-For more information about the Angular Router, see [Routing & Navigation](guide/router "Routing & Navigation guide"). +Para obtener más información sobre el Angular Router, consulta [Enrutamiento y Navegación] (guide/router "Guía de Enrutamiento y Navegación").
+## Próximos pasos -## Next steps +¡Felicidades! Has integrado el enrutamiento en tu tienda en linea. -Congratulations! You have integrated routing into your online store. +* Los productos están vinculados desde la vista de lista de productos a productos individuales. +* Los usuarios pueden hacer clic en el nombre de un producto de la lista para ver los detalles en una nueva vista, con una URL / ruta distinta. -* Products are linked from the product list view to individual products. -* Users can click on a product name from the list to see details in a new view, with a distinct URL/route. - -To continue exploring Angular, choose either of the following options: -* [Continue to the "Managing Data" section](start/start-data "Try it: Managing Data") to add a shopping cart feature, use a service to manage the cart data and use HTTP to retrieve external data for shipping prices. -* [Skip ahead to the Deployment section](start/start-deployment "Try it: Deployment") to deploy your app to Firebase or move to local development. +Para continuar explorando Angular, elige cualquiera de las siguientes opciones: +* [Continuar con la sección "Manejo de Datos"] (start/start-data "Pruébalo: Manejo de datos") para agregar una función de carrito de compras, usa un servicio para administrar los datos del carrito y usa HTTP para recuperar datos externos para los precios del envío. +* [Ir a la sección Despliegue] (start/start-deployment "Pruébalo: Despliegue") para implementar su aplicación en Firebase o pasar al desarrollo local.