3

我正在使用 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 代码。提前致谢。

4

0 回答 0