Sunday, 30 April 2017

Angular2 - Handling API Response

Good afternoon! I'm new in Angular 2, so I'm sorry in advance if my question is generic. I cannot figure out how to handle an API response.

My NodeJS Server API function is (Checked and works fine):

router.get('/appointment/:iatreio/:time', function(req, res, next) {
   var paramIatreio = req.params.iatreio;
   var paramTime = req.params.time;

   db.appointments.findOne({iatreio: paramIatreio, time: req.params.time}, function(err, resultFound) {      
     if (err) { res.send(err); }
     if (resultFound) {
        res.json(true);  // 1st Question: For best practice, res.json(true) or res.send(true)? 
     } else {
        res.json(false);
     }
   });
});

My Angular2 Service:

import { Injectable }           from '@angular/core';
import { Headers , Http }       from '@angular/http';
import { Observable }           from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class AppointmentService {
   constructor(private http: Http) { }
   isBooked(iatreio: string, time: string): Observable<boolean> {
      return this.http
                 .get('http://localhost:3000/appointment/'+iatreio+'/'+time)
                 .map(); //2nd Question: What inside map()?
   }
} // end of Service

Component Function

isBooked(selectedIatreio: string, selectedTime: string): boolean {
this.appointmentService
    .isBooked(selectedIatreio, selectedTime)
    .subscribe(() => {}); //3rd Question: What inside subscribe()?
}

My final goal is the "isBooked(...)" function of my Component to be called and to return true or false. I have seen the code in the examples in the Angular2 site, but I'm a little confused on my case.

Can Service function return directly a true or false value or it has to be an Observable?? Map() function is necessary??

Generally, my thinking is right?? Or my goal can be accomplished more easily??

Thank you a lot for your time!!



via Kostas_Me_

No comments:

Post a Comment