SlideShare una empresa de Scribd logo
AngularJS
Rutas
Álvaro Alonso
Contenidos
 Rutas
 Conexión con servidores de backend
2
Rutas
 Módulo ngRoute
 Servicios y directivas para rutas en aplicaciones Angular
 Mantiene la aplicación tipo SPA (Single Page Application)
 Disponible en
 http://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js
 El nuevo Component Router está deprecado.
3
Rutas
 Insertar dependencia del módulo ngRoute
 Configurar rutas con $routeProvider
 Las vistas van a ng-view
4
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.html"
})
.when("/red", {
templateUrl : "red.html"
});
});
<div ng-view></div>
Rutas
 Enlaces en el template
5
<body ng-app="myApp">
<a href="#/">Home</a>
<a href="#resource1">Resource1</a>
<div ng-view></div>
</body>
Rutas
 Definir un controlador para cada vista
 El controlador recibe parámetros como
 $route, $routeParams, $location
6
app.config(function($routeProvider) {
$routeProvider
.when("/items/:itemId", {
templateUrl : ”items.html”,
controller: “itemsController”
});
});
.controller(’itemsController', function ($scope, $routeParams) {
$scope.params = $routeParams; // {“itemId”: ….}
})
Rutas
 Método otherwise
7
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.html"
})
.otherwise({
templateUrl : ”notFound.html"
});
});
EJEMPLO
Rutas
8
EJERCICIO
Rutas
9
 Añadir en la aplicación una barra de navegación con dos pestañas
 Paciente
 contiene la información que teníamos hasta ahora
 Lista de pacientes
 de momento es una vista con una lista de pacientes inventada
 Cada una de las pestañas debe tener su propio controlador
 Paciente
 El conotrolador que tenía hasta ahora
 Lista de pacientes
 Un nuevo controlador que de momento está vacío
 En caso de utilizar una ruta diferente
 Devolver mensaje 404 not found
Resolve
 Mapa de dependencias que se inyecta en el controlador de la ruta
10
.when('/resource1', {
templateUrl: ’res1.html',
controller: ’res1Controller',
resolve: {
”resource1": function () {
return [’item1', ’item2'];
}
}
})
….
.controller('res1Controller', function ($scope, resource1) {
$scope. resource1 = resource1;
});
Resolve
 Si alguna de las dependencias es una promesa el router espera a
 que todas ellas se resuelvan
 o a que una de ellas sea rechazada
11
.when('/resource1', {
templateUrl: ’res1.html',
controller: ’res1Controller',
resolve: {
”resource1": function ($q) {
var deferred = $q.defer();
setInterval(function() {
deferred.resolve();
}, 3000);
return deferred.promise;
}
}
})
Usando un backend
 Los modelos de datos suelen pedirse a un backend que mantiene la
persistencia
 El servicio $http permite realizar llamadas REST
12
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
…
}, function errorCallback(response) {
…
});
response {
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
}
EJEMPLO
Backend
13
EJERCICIO
Rutas y backend
14
 Ahora la pestaña Lista de pacientes incluirá una lista obtenida del servicio
 https://jsonplaceholder.typicode.com/
 Asociar la URL del servicio a una constante del módulo
 .value(’name', ’value’)
 Opcional
 Crear un servicio que haga el fetch de los datos de la lista
 Ejemplo: https://angularjs.org/#wire-up-a-backend
Documentación
 APIs básicos de routing
 http://www.w3schools.com/angular/angular_routing.asp
 Provider de rutas
 https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
 Servicio de promesas
 https://docs.angularjs.org/api/ng/service/$q
 Servicio HTTP
 https://docs.angularjs.org/api/ng/service/$http
 Servicio resource (más alto niveo que $http)
 https://docs.angularjs.org/api/ngResource/service/$resource
15
AngularJS
Rutas
Álvaro Alonso

Más contenido relacionado

PPTX
Curso AngularJS - 3. módulos y controladores
PPTX
Curso AngularJS - 7. temas avanzados
PPTX
Curso AngularJS - 4. filtros y servicios
PPTX
Curso AngularJS - 2. conceptos básicos
PDF
Api De Google Calendar
PPT
Angularjs Lógica de negocio
PPTX
Angular Conceptos Practicos 1
PDF
Javascript y AJAX en Wordpress
Curso AngularJS - 3. módulos y controladores
Curso AngularJS - 7. temas avanzados
Curso AngularJS - 4. filtros y servicios
Curso AngularJS - 2. conceptos básicos
Api De Google Calendar
Angularjs Lógica de negocio
Angular Conceptos Practicos 1
Javascript y AJAX en Wordpress

La actualidad más candente (20)

KEY
Introducción a Flask
PPTX
KEY
Introducción a DJango
PDF
Java Web Lección 02 - JSP
PDF
ASP.NET MVC - Introducción a ASP.NET MVC
PDF
Cómo domar SonataAdminBundle
PDF
ASP.NET MVC - introduccion al web api
PDF
ASP.NET MVC - validacion de datos
PDF
Conceptos basicos en CakePHP
PDF
ASP.NET MVC - AJAX
PPTX
Curso AngularJS - 6. formularios
PPTX
Curso AngularJS - 1. introducción
PDF
ASP.NET MVC - areas, manejo de estado
PDF
Login social con node.js
PDF
Aplicación abc. asp net mvc 3
PDF
Java servlets
PDF
Curso de Struts2: Unidad Didáctica 00 Introduccion
PPT
Jsf
ODP
Introducción a Flask
Introducción a DJango
Java Web Lección 02 - JSP
ASP.NET MVC - Introducción a ASP.NET MVC
Cómo domar SonataAdminBundle
ASP.NET MVC - introduccion al web api
ASP.NET MVC - validacion de datos
Conceptos basicos en CakePHP
ASP.NET MVC - AJAX
Curso AngularJS - 6. formularios
Curso AngularJS - 1. introducción
ASP.NET MVC - areas, manejo de estado
Login social con node.js
Aplicación abc. asp net mvc 3
Java servlets
Curso de Struts2: Unidad Didáctica 00 Introduccion
Jsf
Publicidad

Destacado (14)

PPTX
WOOP: REWARDS REDEMPTION PROCESS
PDF
Suva classic conversation set 3
PDF
20160111 ra
PDF
Integrating Tech PD
DOCX
DOCX
สอนใช้ SonyVegas ตัดต่อ VDO
PPTX
Smartcities 2015 - Agence du Numérique
PDF
НЛТР_Новая Москва_Моделирование
PPTX
Lesson 5 - Installing Keyrock in your own infrastructure
PPTX
PDF
Новая Москва
PPT
Solidification
PPTX
Paralinguistics
PDF
solution manual of mechanics of material by beer johnston
WOOP: REWARDS REDEMPTION PROCESS
Suva classic conversation set 3
20160111 ra
Integrating Tech PD
สอนใช้ SonyVegas ตัดต่อ VDO
Smartcities 2015 - Agence du Numérique
НЛТР_Новая Москва_Моделирование
Lesson 5 - Installing Keyrock in your own infrastructure
Новая Москва
Solidification
Paralinguistics
solution manual of mechanics of material by beer johnston
Publicidad

Similar a Curso AngularJS - 5. rutas (20)

PPTX
Introducción a AngularJS
PPTX
Advanced angular 1
PDF
Angular js
PDF
Desarrollo de aplicaciones multiplataforma 2/2
PDF
Curso Básico de AngularJS
PDF
deSymfony 2013 - Creando aplicaciones web desde otro ángulo con Symfony y A...
PPTX
Ruby on Rails y AngularJS
PDF
Semana 2 Configuración entorno de desarrollo
PPTX
Presentacion node
PPTX
Expo node js
PDF
JAVA ANGULAR - CURSO JAVASCRIPT AVANZADO
PPTX
Javascript + Angular Sesion 6
PDF
003-Introduccion-Angular.pdf
PPTX
Introduccion a AngularJS
PDF
Introducciòn a AngularJS
PDF
Curso Angular 9 - CodeURJC - Marzo 2020
PDF
Angular js
PPTX
Angular Conceptos Practicos 2
PDF
WordCamp Santander 2016 - Aplicaciones web con AngularJS y la REST API de Wor...
Introducción a AngularJS
Advanced angular 1
Angular js
Desarrollo de aplicaciones multiplataforma 2/2
Curso Básico de AngularJS
deSymfony 2013 - Creando aplicaciones web desde otro ángulo con Symfony y A...
Ruby on Rails y AngularJS
Semana 2 Configuración entorno de desarrollo
Presentacion node
Expo node js
JAVA ANGULAR - CURSO JAVASCRIPT AVANZADO
Javascript + Angular Sesion 6
003-Introduccion-Angular.pdf
Introduccion a AngularJS
Introducciòn a AngularJS
Curso Angular 9 - CodeURJC - Marzo 2020
Angular js
Angular Conceptos Practicos 2
WordCamp Santander 2016 - Aplicaciones web con AngularJS y la REST API de Wor...

Más de Álvaro Alonso González (15)

PPTX
Adding identity management and access control to your app
PPTX
KeyRock and Wilma - Openstack-based Identity Management in FIWARE
PPTX
Lesson 6 - How to register your sensors in account portal
PPTX
Keyrock - Lesson 3. Applications. How to create OAuth2 tokens.
PPTX
Keyrock - Lesson 1. Introduction
PPTX
Cloud Portal - Lesson 5. Advanced tasks
PPTX
Cloud Portal - Lesson 4. Managing Storage
PPTX
Cloud Portal - Lesson 2. Cloud Portal Overview
PPTX
Cloud Portal - Lesson 1. Introduction
PPTX
Cloud Portal - Lesson 3. Launching an Instance
PPTX
Primeros pasos con Docker
PDF
Introducción al Protocolo OAuth 2.0
PPTX
Adding Identity Management and Access Control to your Application
PPTX
Adding Identity Management and Access Control to your Application - Exersices
PPTX
Setting Up your Cloud Environment using the FIWARE Lab Cloud Portal
Adding identity management and access control to your app
KeyRock and Wilma - Openstack-based Identity Management in FIWARE
Lesson 6 - How to register your sensors in account portal
Keyrock - Lesson 3. Applications. How to create OAuth2 tokens.
Keyrock - Lesson 1. Introduction
Cloud Portal - Lesson 5. Advanced tasks
Cloud Portal - Lesson 4. Managing Storage
Cloud Portal - Lesson 2. Cloud Portal Overview
Cloud Portal - Lesson 1. Introduction
Cloud Portal - Lesson 3. Launching an Instance
Primeros pasos con Docker
Introducción al Protocolo OAuth 2.0
Adding Identity Management and Access Control to your Application
Adding Identity Management and Access Control to your Application - Exersices
Setting Up your Cloud Environment using the FIWARE Lab Cloud Portal

Último (20)

DOCX
Trabajo colaborativo Grupo #2.docxmkkkkkkl
PPTX
Administración se srevidores de apliaciones
PPTX
IA de Cine - Como MuleSoft y los Agentes estan redefiniendo la realidad
PDF
ACTIVIDAD 2.pdf j
PPT
Que son las redes de computadores y sus partes
PDF
diagrama de pareto.pdf valerie giraldo diaz
PPTX
RAP01 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
PDF
SAP Transportation Management para LSP, TM140 Col18
PDF
Conceptos básicos de programación tecnología.pdf
PDF
clase auditoria informatica 2025.........
PPT
introduccion a las_web en el 2025_mejoras.ppt
PDF
taller de informática - LEY DE OHM
PDF
Liceo departamental MICRO BIT (1) 2.pdfbbbnn
PPTX
Presentación PASANTIAS AuditorioOO..pptx
PDF
Plantilla para Diseño de Narrativas Transmedia.pdf
PPTX
historia_web de la creacion de un navegador_presentacion.pptx
PDF
Aristoteles-y-su-forma-de-entender-el-conocimiento-y-las-personas.pdf
PDF
La electricidad y la electrónica .pdf n
PDF
Influencia-del-uso-de-redes-sociales.pdf
PPTX
REDES INFORMATICAS REDES INFORMATICAS.pptx
Trabajo colaborativo Grupo #2.docxmkkkkkkl
Administración se srevidores de apliaciones
IA de Cine - Como MuleSoft y los Agentes estan redefiniendo la realidad
ACTIVIDAD 2.pdf j
Que son las redes de computadores y sus partes
diagrama de pareto.pdf valerie giraldo diaz
RAP01 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
SAP Transportation Management para LSP, TM140 Col18
Conceptos básicos de programación tecnología.pdf
clase auditoria informatica 2025.........
introduccion a las_web en el 2025_mejoras.ppt
taller de informática - LEY DE OHM
Liceo departamental MICRO BIT (1) 2.pdfbbbnn
Presentación PASANTIAS AuditorioOO..pptx
Plantilla para Diseño de Narrativas Transmedia.pdf
historia_web de la creacion de un navegador_presentacion.pptx
Aristoteles-y-su-forma-de-entender-el-conocimiento-y-las-personas.pdf
La electricidad y la electrónica .pdf n
Influencia-del-uso-de-redes-sociales.pdf
REDES INFORMATICAS REDES INFORMATICAS.pptx

Curso AngularJS - 5. rutas

  • 2. Contenidos  Rutas  Conexión con servidores de backend 2
  • 3. Rutas  Módulo ngRoute  Servicios y directivas para rutas en aplicaciones Angular  Mantiene la aplicación tipo SPA (Single Page Application)  Disponible en  http://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js  El nuevo Component Router está deprecado. 3
  • 4. Rutas  Insertar dependencia del módulo ngRoute  Configurar rutas con $routeProvider  Las vistas van a ng-view 4 var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.html" }) .when("/red", { templateUrl : "red.html" }); }); <div ng-view></div>
  • 5. Rutas  Enlaces en el template 5 <body ng-app="myApp"> <a href="#/">Home</a> <a href="#resource1">Resource1</a> <div ng-view></div> </body>
  • 6. Rutas  Definir un controlador para cada vista  El controlador recibe parámetros como  $route, $routeParams, $location 6 app.config(function($routeProvider) { $routeProvider .when("/items/:itemId", { templateUrl : ”items.html”, controller: “itemsController” }); }); .controller(’itemsController', function ($scope, $routeParams) { $scope.params = $routeParams; // {“itemId”: ….} })
  • 7. Rutas  Método otherwise 7 app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.html" }) .otherwise({ templateUrl : ”notFound.html" }); });
  • 9. EJERCICIO Rutas 9  Añadir en la aplicación una barra de navegación con dos pestañas  Paciente  contiene la información que teníamos hasta ahora  Lista de pacientes  de momento es una vista con una lista de pacientes inventada  Cada una de las pestañas debe tener su propio controlador  Paciente  El conotrolador que tenía hasta ahora  Lista de pacientes  Un nuevo controlador que de momento está vacío  En caso de utilizar una ruta diferente  Devolver mensaje 404 not found
  • 10. Resolve  Mapa de dependencias que se inyecta en el controlador de la ruta 10 .when('/resource1', { templateUrl: ’res1.html', controller: ’res1Controller', resolve: { ”resource1": function () { return [’item1', ’item2']; } } }) …. .controller('res1Controller', function ($scope, resource1) { $scope. resource1 = resource1; });
  • 11. Resolve  Si alguna de las dependencias es una promesa el router espera a  que todas ellas se resuelvan  o a que una de ellas sea rechazada 11 .when('/resource1', { templateUrl: ’res1.html', controller: ’res1Controller', resolve: { ”resource1": function ($q) { var deferred = $q.defer(); setInterval(function() { deferred.resolve(); }, 3000); return deferred.promise; } } })
  • 12. Usando un backend  Los modelos de datos suelen pedirse a un backend que mantiene la persistencia  El servicio $http permite realizar llamadas REST 12 $http({ method: 'GET', url: '/someUrl' }).then(function successCallback(response) { … }, function errorCallback(response) { … }); response { data – {string|Object} – The response body transformed with the transform functions. status – {number} – HTTP status code of the response. headers – {function([headerName])} – Header getter function. config – {Object} – The configuration object that was used to generate the request. statusText – {string} – HTTP status text of the response. }
  • 14. EJERCICIO Rutas y backend 14  Ahora la pestaña Lista de pacientes incluirá una lista obtenida del servicio  https://jsonplaceholder.typicode.com/  Asociar la URL del servicio a una constante del módulo  .value(’name', ’value’)  Opcional  Crear un servicio que haga el fetch de los datos de la lista  Ejemplo: https://angularjs.org/#wire-up-a-backend
  • 15. Documentación  APIs básicos de routing  http://www.w3schools.com/angular/angular_routing.asp  Provider de rutas  https://docs.angularjs.org/api/ngRoute/provider/$routeProvider  Servicio de promesas  https://docs.angularjs.org/api/ng/service/$q  Servicio HTTP  https://docs.angularjs.org/api/ng/service/$http  Servicio resource (más alto niveo que $http)  https://docs.angularjs.org/api/ngResource/service/$resource 15