2017-04-30 19 views
0

おはようございます!私はAngular 2で新しくなったので、私の質問が一般的なものであれば事前に申し訳なく思っています。私はAPIの応答を処理する方法を理解できません。角度2 - API応答の処理

マイNodeJSサーバーAPI関数は、(チェックと正常に動作します)です:

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); 
    } 
    }); 
}); 

マイAngular2サービス:

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 

コンポーネント機能

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

私の最終目標です " isBooked(...) "関数を呼び出すとtrueまたはfalseを返します。私はAngular2サイトの例でコードを見てきましたが、私の場合は少し混乱しています。

Can Service関数は、真または偽の値を直接返したり、Observableでなければなりませんか? Map()関数は必要ですか?

一般的に、私の考えは正しいですか?または私の目標はより簡単に達成できますか?

ありがとうございます! /:

+0

から放出されたデータを返します変換するために使用されます/stackoverflow.com/a/33942337/5079380)。それはあなたが必要とするすべての答えを持っています。 –

+2

[Angular2ハンドリングhttp応答]の可能な複製(http://stackoverflow.com/questions/33941836/angular2-handling-http-response) –

答えて

0

mapは、この[解答](HTTPを参照してくださいあなたは

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

購読を探しモデルへの応答がサービス

isBooked(selectedIatreio: string, selectedTime: string): boolean { 
this.appointmentService 
    .isBooked(selectedIatreio, selectedTime) 
    .subscribe((data) => { 
      //your operation 
      console.log(data); 
    }); 
}