如何在Observable错误中延迟响应?

时间:2016-06-08 14:43:32

标签: angular rxjs observable angular2-http

我正在使用observables在angular2中创建一个登录服务,但我需要一种方法来延迟错误的响应。实际上我的服务看起来像这样:

import {Injectable} from '@angular/core';
import {Location} from '@angular/common';
import {Headers, RequestOptions, Http} from "@angular/http";
import {Router} from '@angular/router'
import {Observable} from "rxjs/Rx";

import {Urls} from "../shared/Urls";

@Injectable()

export class LoginService {

    constructor(private http:Http, private router:Router, private location:Location) {
    }

    loginHospital(email:string, contrasena:string) {
        let url = `${Urls.urlBase + Urls.loginHospital}`;
        let body = JSON.stringify({email, contrasena});
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(url, body, options)
            .delay(2000) //it doesn't work :(
            .map(res => res.json())
            .map(res => {
                if (res.error) {
                    return this.handleError(res.error);
                }
                localStorage.setItem('jwt', res.data.token);
                return true;
            }).catch(this.handleError);
    }

    logout() {....}

    private handleError(error) {
        error = error.json().error;
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Error en el servidor >:v';
        console.error(errMsg);

        return Observable.throw(errMsg);

    }
}

实际上,“如果呼叫有正确的数据,则不会延迟。但如果收到错误代码,任何呼叫都将被延迟”。

在服务器端,我发送登录错误的403代码。提前谢谢。

0 个答案:

没有答案