top of page

Llamar APIs Get y Post con Typescript y C#

Codigo para crear un servicio que para request GET y Post.

Codigo de un servicio en Typescript

//Archivo  Usuario.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })


export class UsuarioService {

    private apiUrl = 'api/Usuario/';
    constructor(private http: HttpClient) { }

//Get para demandar la informacion del usuario

  public UsuarioGet(isuarioID): Observable<any> {
        const params = new HttpParams()
            .set('isuarioID', isuarioID)
      let jsonData = this.http.get<any>(this.apiUrl + 'UsuarioGet', { params }).pipe(map(data => { return data }));
        return jsonData;;
    };

//POST Para actualizar datos

 

    public UsuarioUpdate(formData): Observable<any> {
        let jsonData
= this.http.post<any>(this.apiUrl + 'UsuarioUpdate', formData).pipe(map(data => { return data }));
        return jsonData;;
    };

 

//Archivo  Usuario.component.ts

import { Component, OnInit } from '@angular/core';
import { UsuarioService } from '../Services/UsuarioService';

@Component({
  selector: 'app-usuario',
  templateUrl: './usuario.component.html',
})


export class UsuarioComponent implements OnInit {
  user = "";
  userID = 0;
  userEmail = "";
  constructor(private service: UsuarioService) {

  }
  ngOnInit() {
    this.getUsuario(99);
  }
  getUsuario(isuarioID:number) {
    this.service.UsuarioGet(isuarioID).subscribe(response => {
      this.user = response.body;
      console.log(this.user);

    })
  }

UpdateUsuario() {
        let us = {
            user: "John Doe",
            UserID: 505,
            userEmail: "johnD@myemail.com"
        }

        let formData: FormData = new FormData();
        formData.append('user', us.user),
        formData.append('UserID', us.UserID.toString()),
        formData.append('userEmail', us.userEmail);

        this.service.UsuarioUpdate(formData).subscribe(response => {

            if (response) {
                alert("success");
            }

        });
    }


}

//Archivo  C# controller in the same project

 public class UsuarioController  
    {

[HttpPost]
        public string UsuarioUpdate()
        {
       
            try
            {
                var user = Request.Form["user"];
                var UserID = Request.Form["UserID"];
                var userEmail = Request.Form["userEmail"];
                
                // todo

                return JsonConvert.SerializeObject("finished");
                
            }
            catch (Exception ex)
            {                             
                throw;
            }
        }

}

bottom of page