0

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!!

2

1 Answer 1

0

map is used to convert the response into the model which you look for

isBooked(iatreio: string, time: string): Observable<boolean> {
      return this.http
                 .get('http://localhost:3000/appointment/'+iatreio+'/'+time)
                 .map((response)=><boolean>response.json()); 
   }

subscribe will return the data emitted by the service

isBooked(selectedIatreio: string, selectedTime: string): boolean {
this.appointmentService
    .isBooked(selectedIatreio, selectedTime)
    .subscribe((data) => { 
          //your operation
          console.log(data);
     }); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.