Advertisement
Guest User

Typescript get and post

a guest
Mar 14th, 2017
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ### COMPONENTE LOGIN ###
  2.  
  3. import { Component, OnInit } from '@angular/core';
  4. import { Http, Headers, Response,URLSearchParams } from '@angular/http';
  5. import { Observable } from 'rxjs/Observable';
  6. import 'rxjs/add/operator/map'
  7. import { AuthenticationService } from '../_servicios/authentication.service';
  8. import { User } from '../_model/user';
  9. @Component({
  10.   selector: 'app-login',
  11.   templateUrl: './login.component.html',
  12.   styleUrls: ['./login.component.css']
  13. })
  14. export class LoginComponent implements OnInit {
  15.   model: any = {}; // Define un modelo para la información introducida en el formulario
  16.   cargando = false;
  17.   response;
  18.   constructor( private authenticationService: AuthenticationService) { }
  19.  
  20.   ngOnInit() {
  21.   // Bloque de código que se carga al ejecutar la página
  22.   }
  23.  
  24.  
  25.   // Funcion de login se ejecuta al hacer submit en el formulario de acceso
  26.   login(){
  27.     this.cargando = true
  28.  
  29.     // Llamamos al servicio de autenticación pasandole los datos introducidos en el formulario
  30.     this.authenticationService.POST(this.model.username, this.model.password)
  31.  
  32.  
  33.   }
  34.   listar() {
  35.     this.authenticationService.GET().subscribe(  res => this.response = res)
  36.     alert(this.response)
  37.   }
  38. }
  39.  
  40.  
  41.  
  42. ###### SERVICIO AUTENTICACION #######
  43.  
  44. import { Injectable } from '@angular/core';
  45. import { Http, Headers, Response,URLSearchParams } from '@angular/http';
  46. import { Observable } from 'rxjs/Observable';
  47. import 'rxjs/add/operator/map'
  48.  
  49. @Injectable()
  50. export class AuthenticationService {
  51.   respuesta = "";
  52.   data;
  53.   users = Array<Object>()
  54.   constructor( private http: Http ) { }
  55.  
  56.   POST(username: string, password: string) {
  57.  
  58.     // Crea un body con los parámetros que enviaremos al PHP (usuario y contraseña)
  59.     let urlSearchParams = new URLSearchParams();
  60.     let url = 'http://localhost/proyecto/Parser/src/app/backend/handler.php';
  61.     // Añadimos los campos
  62.     urlSearchParams.append('usuario', username);
  63.     urlSearchParams.append('password',  password);
  64.     let body = urlSearchParams.toString() // Añadimos los parametros a la variable body pasandolos a string
  65.  
  66.     // Generamos los headers
  67.     var headers = new Headers();
  68.     headers.append('Content-Type', 'application/x-www-form-urlencoded');
  69.  
  70.     alert("POST info: "+body);
  71.  
  72.     // Crea una peticion post a la PHP con el body y los headers, devuelve el estado de la peticion
  73.      return this.http
  74.       .post(url ,
  75.         body, {
  76.           headers: headers
  77.         })
  78.         .map((res:Response) => this.respuesta = res.json())
  79.             .subscribe(users => this.users = users);
  80.       // En un principio este método sería opcional
  81.   }
  82.   GET() {
  83.     const headers = new Headers();
  84.     headers.append('Content-Type', 'application/x-www-form-urlencoded');
  85.     headers.append('Access-Control-Allow-Headers', 'Content-Type');
  86.     headers.append('Access-Control-Allow-Methods', 'GET');
  87.     headers.append('Access-Control-Allow-Origin', '*');
  88.  
  89.  
  90.     alert(this.users)
  91.     let URL = 'http://localhost/proyecto/Parser/src/app/backend/list.json';
  92.     return this.http.get(URL, {headers: headers}).map(res => res.json())
  93.           .subscribe(data => this.data = data,
  94.                     err => console.log(err),
  95.                     () => console.log('Completed'));
  96.  
  97.   }
  98.  
  99.  
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement