下午好!我是Angular 2的新手,所以如果我的问题是通用的,我很抱歉。我无法弄清楚如何处理API响应。
我的NodeJS Server 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()?
}
我的最终目标是调用我的Component的“isBooked(...)”函数并返回true或false。我在Angular2网站的例子中看到了代码,但我对我的情况有点困惑。
服务函数可以直接返回true或false值,还是必须是Observable? Map()函数是必要的??
一般来说,我的想法是正确的?或者我的目标可以更轻松地完成?
非常感谢你的时间!!
答案 0 :(得分:0)
map
用于将响应转换为您要查找的模型
isBooked(iatreio: string, time: string): Observable<boolean> {
return this.http
.get('http://localhost:3000/appointment/'+iatreio+'/'+time)
.map((response)=><boolean>response.json());
}
subscribe将返回服务发出的数据
isBooked(selectedIatreio: string, selectedTime: string): boolean {
this.appointmentService
.isBooked(selectedIatreio, selectedTime)
.subscribe((data) => {
//your operation
console.log(data);
});
}