SlideShare ist ein Scribd-Unternehmen logo
1 von 16
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Introducción a Flask
Introducción a FlaskIntroducción a Flask
Introducción a Flask
 
Angularjs
AngularjsAngularjs
Angularjs
 
Introducción a DJango
Introducción a DJangoIntroducción a DJango
Introducción a DJango
 
Java Web Lección 02 - JSP
Java Web Lección 02 - JSPJava Web Lección 02 - JSP
Java Web Lección 02 - JSP
 
ASP.NET MVC - Introducción a ASP.NET MVC
ASP.NET MVC - Introducción a ASP.NET MVCASP.NET MVC - Introducción a ASP.NET MVC
ASP.NET MVC - Introducción a ASP.NET MVC
 
Cómo domar SonataAdminBundle
Cómo domar SonataAdminBundleCómo domar SonataAdminBundle
Cómo domar SonataAdminBundle
 
ASP.NET MVC - introduccion al web api
ASP.NET MVC - introduccion al web apiASP.NET MVC - introduccion al web api
ASP.NET MVC - introduccion al web api
 
ASP.NET MVC - validacion de datos
ASP.NET MVC - validacion de datosASP.NET MVC - validacion de datos
ASP.NET MVC - validacion de datos
 
Conceptos basicos en CakePHP
Conceptos basicos en CakePHPConceptos basicos en CakePHP
Conceptos basicos en CakePHP
 
ASP.NET MVC - AJAX
ASP.NET MVC - AJAXASP.NET MVC - AJAX
ASP.NET MVC - AJAX
 
Curso AngularJS - 6. formularios
Curso AngularJS - 6. formulariosCurso AngularJS - 6. formularios
Curso AngularJS - 6. formularios
 
Curso AngularJS - 1. introducción
Curso AngularJS - 1. introducciónCurso AngularJS - 1. introducción
Curso AngularJS - 1. introducción
 
ASP.NET MVC - areas, manejo de estado
ASP.NET MVC - areas, manejo de estadoASP.NET MVC - areas, manejo de estado
ASP.NET MVC - areas, manejo de estado
 
Login social con node.js
Login social con node.jsLogin social con node.js
Login social con node.js
 
Aplicación abc. asp net mvc 3
Aplicación abc. asp net mvc 3Aplicación abc. asp net mvc 3
Aplicación abc. asp net mvc 3
 
Crear modulos
Crear modulosCrear modulos
Crear modulos
 
Java servlets
Java servletsJava servlets
Java servlets
 
Curso de Struts2: Unidad Didáctica 00 Introduccion
Curso de Struts2: Unidad Didáctica 00 IntroduccionCurso de Struts2: Unidad Didáctica 00 Introduccion
Curso de Struts2: Unidad Didáctica 00 Introduccion
 
Jsf
JsfJsf
Jsf
 
JSP
JSPJSP
JSP
 

Andere mochten auch

WOOP: REWARDS REDEMPTION PROCESS
WOOP: REWARDS REDEMPTION PROCESSWOOP: REWARDS REDEMPTION PROCESS
WOOP: REWARDS REDEMPTION PROCESSKe Pang Lew
 
Suva classic conversation set 3
Suva classic conversation set 3Suva classic conversation set 3
Suva classic conversation set 3GOODDEGG®
 
НЛТР_Новая Москва_Моделирование
НЛТР_Новая Москва_МоделированиеНЛТР_Новая Москва_Моделирование
НЛТР_Новая Москва_МоделированиеKsenya Khlobysheva
 
Lesson 5 - Installing Keyrock in your own infrastructure
Lesson 5 - Installing Keyrock in your own infrastructure Lesson 5 - Installing Keyrock in your own infrastructure
Lesson 5 - Installing Keyrock in your own infrastructure Álvaro Alonso González
 
Paralinguistics
Paralinguistics Paralinguistics
Paralinguistics Meet Shah
 
7 stress transformations- Mechanics of Materials - 4th - Beer
7 stress transformations- Mechanics of Materials - 4th - Beer7 stress transformations- Mechanics of Materials - 4th - Beer
7 stress transformations- Mechanics of Materials - 4th - BeerNhan Tran
 
9 beam deflection- Mechanics of Materials - 4th - Beer
9 beam deflection- Mechanics of Materials - 4th - Beer9 beam deflection- Mechanics of Materials - 4th - Beer
9 beam deflection- Mechanics of Materials - 4th - BeerNhan Tran
 
2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - BeerNhan Tran
 
solution manual of mechanics of material by beer johnston
solution manual of mechanics of material by beer johnstonsolution manual of mechanics of material by beer johnston
solution manual of mechanics of material by beer johnstonZia ur rahman
 

Andere mochten auch (17)

WOOP: REWARDS REDEMPTION PROCESS
WOOP: REWARDS REDEMPTION PROCESSWOOP: REWARDS REDEMPTION PROCESS
WOOP: REWARDS REDEMPTION PROCESS
 
Suva classic conversation set 3
Suva classic conversation set 3Suva classic conversation set 3
Suva classic conversation set 3
 
20160111 ra
20160111 ra20160111 ra
20160111 ra
 
Integrating Tech PD
Integrating Tech PDIntegrating Tech PD
Integrating Tech PD
 
Itnew
ItnewItnew
Itnew
 
สอนใช้ SonyVegas ตัดต่อ VDO
สอนใช้ SonyVegas ตัดต่อ VDO สอนใช้ SonyVegas ตัดต่อ VDO
สอนใช้ SonyVegas ตัดต่อ VDO
 
Smartcities 2015 - Agence du Numérique
Smartcities 2015 - Agence du NumériqueSmartcities 2015 - Agence du Numérique
Smartcities 2015 - Agence du Numérique
 
НЛТР_Новая Москва_Моделирование
НЛТР_Новая Москва_МоделированиеНЛТР_Новая Москва_Моделирование
НЛТР_Новая Москва_Моделирование
 
Lesson 5 - Installing Keyrock in your own infrastructure
Lesson 5 - Installing Keyrock in your own infrastructure Lesson 5 - Installing Keyrock in your own infrastructure
Lesson 5 - Installing Keyrock in your own infrastructure
 
Msm
MsmMsm
Msm
 
Новая Москва
Новая МоскваНовая Москва
Новая Москва
 
Solidification
SolidificationSolidification
Solidification
 
Paralinguistics
Paralinguistics Paralinguistics
Paralinguistics
 
7 stress transformations- Mechanics of Materials - 4th - Beer
7 stress transformations- Mechanics of Materials - 4th - Beer7 stress transformations- Mechanics of Materials - 4th - Beer
7 stress transformations- Mechanics of Materials - 4th - Beer
 
9 beam deflection- Mechanics of Materials - 4th - Beer
9 beam deflection- Mechanics of Materials - 4th - Beer9 beam deflection- Mechanics of Materials - 4th - Beer
9 beam deflection- Mechanics of Materials - 4th - Beer
 
2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer
 
solution manual of mechanics of material by beer johnston
solution manual of mechanics of material by beer johnstonsolution manual of mechanics of material by beer johnston
solution manual of mechanics of material by beer johnston
 

Ähnlich wie Curso AngularJS - 5. rutas

Ähnlich wie Curso AngularJS - 5. rutas (20)

Introducción a AngularJS
Introducción a AngularJS Introducción a AngularJS
Introducción a AngularJS
 
Curso Básico de AngularJS
Curso Básico de AngularJSCurso Básico de AngularJS
Curso Básico de AngularJS
 
SEMINARIO: Servicios REST. Bases de la tecnología y soporte con Spring MVC
SEMINARIO: Servicios REST. Bases de la tecnología y soporte con Spring MVCSEMINARIO: Servicios REST. Bases de la tecnología y soporte con Spring MVC
SEMINARIO: Servicios REST. Bases de la tecnología y soporte con Spring MVC
 
Introducción a AngularJS
Introducción a AngularJSIntroducción a AngularJS
Introducción a AngularJS
 
JavaScript no es Vietnam
JavaScript no es VietnamJavaScript no es Vietnam
JavaScript no es Vietnam
 
Drupal7 para desarrolladores
Drupal7 para desarrolladoresDrupal7 para desarrolladores
Drupal7 para desarrolladores
 
Servicios web
Servicios webServicios web
Servicios web
 
Segunda sesion
Segunda sesionSegunda sesion
Segunda sesion
 
Servicios web
Servicios webServicios web
Servicios web
 
Servicios web
Servicios webServicios web
Servicios web
 
UDA-Componentes RUP. Menú contextual
UDA-Componentes RUP. Menú contextualUDA-Componentes RUP. Menú contextual
UDA-Componentes RUP. Menú contextual
 
Servicios web
Servicios webServicios web
Servicios web
 
Laravel 5.1
Laravel 5.1Laravel 5.1
Laravel 5.1
 
Servicio web java php perl google
Servicio web  java php perl googleServicio web  java php perl google
Servicio web java php perl google
 
Hands on Spring 2.5
Hands on Spring 2.5Hands on Spring 2.5
Hands on Spring 2.5
 
Prueba De Aplicaciones Web con Selenium 2 y WebDriver
Prueba De Aplicaciones Web con Selenium 2 y WebDriverPrueba De Aplicaciones Web con Selenium 2 y WebDriver
Prueba De Aplicaciones Web con Selenium 2 y WebDriver
 
04. Implementando APIs HTML5
04. Implementando APIs HTML5 04. Implementando APIs HTML5
04. Implementando APIs HTML5
 
Symfony en Drupal 8 - DrupalCamp Spain
Symfony en Drupal 8 - DrupalCamp Spain Symfony en Drupal 8 - DrupalCamp Spain
Symfony en Drupal 8 - DrupalCamp Spain
 
Clase 1 Programacion Android
Clase 1 Programacion AndroidClase 1 Programacion Android
Clase 1 Programacion Android
 
01 introducción
01 introducción01 introducción
01 introducción
 

Mehr von Álvaro Alonso González

Adding identity management and access control to your app
Adding identity management and access control to your appAdding identity management and access control to your app
Adding identity management and access control to your appÁlvaro Alonso González
 
KeyRock and Wilma - Openstack-based Identity Management in FIWARE
KeyRock and Wilma - Openstack-based Identity Management in FIWAREKeyRock and Wilma - Openstack-based Identity Management in FIWARE
KeyRock and Wilma - Openstack-based Identity Management in FIWAREÁlvaro Alonso González
 
Lesson 6 - How to register your sensors in account portal
Lesson 6 - How to register your sensors in account portalLesson 6 - How to register your sensors in account portal
Lesson 6 - How to register your sensors in account portalÁlvaro Alonso González
 
Keyrock - Lesson 3. Applications. How to create OAuth2 tokens.
Keyrock - Lesson 3. Applications. How to create OAuth2 tokens.Keyrock - Lesson 3. Applications. How to create OAuth2 tokens.
Keyrock - Lesson 3. Applications. How to create OAuth2 tokens.Álvaro Alonso González
 
Cloud Portal - Lesson 2. Cloud Portal Overview
Cloud Portal - Lesson 2. Cloud Portal OverviewCloud Portal - Lesson 2. Cloud Portal Overview
Cloud Portal - Lesson 2. Cloud Portal OverviewÁlvaro Alonso González
 
Cloud Portal - Lesson 3. Launching an Instance
Cloud Portal - Lesson 3. Launching an InstanceCloud Portal - Lesson 3. Launching an Instance
Cloud Portal - Lesson 3. Launching an InstanceÁlvaro Alonso González
 
Adding Identity Management and Access Control to your Application
Adding Identity Management and Access Control to your ApplicationAdding Identity Management and Access Control to your Application
Adding Identity Management and Access Control to your ApplicationÁlvaro Alonso González
 
Adding Identity Management and Access Control to your Application - Exersices
Adding Identity Management and Access Control to your Application - ExersicesAdding Identity Management and Access Control to your Application - Exersices
Adding Identity Management and Access Control to your Application - ExersicesÁlvaro Alonso González
 
Setting Up your Cloud Environment using the FIWARE Lab Cloud Portal
Setting Up your Cloud Environment using the FIWARE Lab Cloud PortalSetting Up your Cloud Environment using the FIWARE Lab Cloud Portal
Setting Up your Cloud Environment using the FIWARE Lab Cloud PortalÁlvaro Alonso González
 

Mehr von Álvaro Alonso González (15)

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

Kürzlich hochgeladen

Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanamcerpam
 
investigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXIinvestigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXIhmpuellon
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxJorgeParada26
 
Buenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptxBuenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptxFederico Castellari
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...JohnRamos830530
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.FlorenciaCattelani
 
Guia Basica para bachillerato de Circuitos Basicos
Guia Basica para bachillerato de Circuitos BasicosGuia Basica para bachillerato de Circuitos Basicos
Guia Basica para bachillerato de Circuitos BasicosJhonJairoRodriguezCe
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estossgonzalezp1
 
redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativanicho110
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21mariacbr99
 

Kürzlich hochgeladen (10)

Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvana
 
investigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXIinvestigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXI
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
 
Buenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptxBuenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptx
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.
 
Guia Basica para bachillerato de Circuitos Basicos
Guia Basica para bachillerato de Circuitos BasicosGuia Basica para bachillerato de Circuitos Basicos
Guia Basica para bachillerato de Circuitos Basicos
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estos
 
redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21
 

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