【问题标题】:Angular2 - Handling API ResponseAngular2 - 处理 API 响应
【发布时间】:2017-09-28 06:38:26
【问题描述】:

下午好!我是 Angular 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(...)”函数并返回真或假。我已经在 Angular2 站点的示例中看到了代码,但我对我的情况有点困惑。

Service 函数可以直接返回 true 或 false 值还是必须是 Observable? Map() 函数是必要的吗??

总的来说,我的想法是对的??或者我的目标可以更轻松地实现??

非常感谢您的宝贵时间!!

【问题讨论】:

标签: node.js angular observable


【解决方案1】:

map 用于将响应转换为您要查找的模型

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

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多