• Ivy Seo

HTTP: GET request-in Angular/Rust

How to pass data in URL and get the data back? (in Angular: front-end / Rust: back-end)


in Angular file: filename.component.ts

export class FilterBarComponent implements OnInit {
 rows = [];
 events: string[] = []; // --- date picker

 addEvent(typestringeventMatDatepickerInputEvent<Date>) {
 this.events.push(${event.value}`);
  }

 SearchBtnClicked(){
 // GET: Get Data from Rust
 this.http 
      .get('http://127.0.0.1:8088/logdata/index/' + this.events.toLocaleString())    // pass date (as String type) in url
      .subscribe(data => { // retrieve returned data
 let data_checkany = data;
 this.rows = data_check; // insert its data into rows[]
      });
  }

in Rust file: main.rs


#[actix_rt::main]
async fn main() -> std::io::Result<()> {

 let _test = HttpServer::new(|| {
   App::new()
      .wrap(
        Cors::new() // <- Construct CORS middleware builder
           .send_wildcard()
           .allowed_methods(vec!["GET", "POST", "PUT"]) // as you need
           .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
            .allowed_header(header::CONTENT_TYPE)
            .max_age(3600)
            .finish(),
        )
 .service(   
// send the data after getting data using the passed date to Angular
     web::resource("/logdata/index/{date}") // date value is passed
      .route(web::get().to(get_date_and_send_logdata)) // call this ()
      .route(web::head().to(|| HttpResponse::MethodNotAllowed())),
            )
    })
    .bind("127.0.0.1:8088")? //To bind to a specific socket address, bind() must be used, and it may be called multiple times.
    .run() /*run() method returns instance of Server type. Methods of server type could be used for managing http server
                pause() - Pause accepting incoming connections
                resume() - Resume accepting incoming connections
                stop() - Stop incoming connection processing, stop all workers and exit
    */
    .await;
 }

get_date_and_send_logdata():

async fn get_date_and_send_logdata(date: web::Path<String>) -> impl Responder {   // send data to Angular
 let m7log_data = get_date_and_its_data(date.into_inner());  
 
    HttpResponse::Ok().json(m7log_data) // return data as JSON 
}

get_date_and_its_data():


pub fn get_date_and_its_data(date: String) -> Vec<M7Log_Data>  {   // get date value
// connect to db
 let conn = Connection::connect(
 "postgresql://UserName:Password@localhost:Port/Database",
        TlsMode::None,
    )
    .unwrap();

// query statement
 let stmt = conn.prepare("SELECT direction, latend, lathemi, lonend,
    lonhemi, mph, county, road, linetype FROM TableName WHERE logdate >= ($1) and logdate <= ($2) ").unwrap();

 let mut vec = Vec::new(); // vec
 
 // passed date format from Angular: 
 // ex) Wed Sep 06 2017 00:00:00 GMT-0700 (Pacific Daylight Time)
 // CONVERT: TIMESTAMP WITHOUT TIMEZONE FORMAT
 let v: Vec<&str> = date // split it in vec
        .split(|c| c == ':' || c == ' ')
        .collect();

 let year: i32 = v[3].parse().unwrap();  // save each items
 let mut month: u32 =1;
 let day: u32 = v[2].parse().unwrap();
 let hour: u32= v[4].parse().unwrap();
 let min: u32=v[5].parse().unwrap();
 let sec: u32=v[6].parse().unwrap();

        if v[1] == "Jan" {
            month = 1;
        }else if v[1] == "Feb" {
            month = 2;

        }else if v[1] == "Mar" {
            month = 3;

        }else if v[1] == "Apr" {
            month = 4;

        }else if v[1] == "May" {
            month = 5;

        }else if v[1] == "Jun" {
            month = 6;

        }else if v[1] == "Jul" {
            month = 7;

        }else if v[1] == "Aug" {
            month = 8;

        }else if v[1] == "Sep" {
            month = 9;

        }else if v[1] == "Oct" {
            month = 10;

        }else if v[1] == "Nov" {
            month = 11;

        }else if v[1] == "Dec" {
            month = 12;

        }

// CONVERT DATE FORMAT
 let dt: NaiveDateTime = NaiveDate::from_ymd(year, month, day).and_hms(hour, min, sec);      // convert to the correct Date format
 let dt2: NaiveDateTime = NaiveDate::from_ymd(year, month, day).and_hms(23, 59, 59);      // convert to the correct Date format + 1 day


 
// GET THE DATA
 for row in &stmt.query(&[&dt, &dt2]).unwrap() { // pass date value : WHERE logdate = $1
 let vals = M7Log_Data {
            direction: row.get(0),
            latend: row.get(1),
            lathemi: row.get(2),
            lonend: row.get(3),
            lonhemi: row.get(4),
            mph: row.get(5),
            county: row.get(6),
            road: row.get(7),
            linetype: row.get(8)
        };
        vec.push(vals);
    }
 return vec; // return data as Vec
}


These are HTTP Methods options: • GET POST PUT HEAD DELETE PATCH OPTIONS