Angular2:如果API返回错误,如何重定向?

时间:2016-04-14 15:35:52

标签: typescript angular angular2-routing angular2-services

在我的服务中,我想描述一下在未经授权的情况下重定向用户时的行为。

export class MessagesService {
    constructor (private http: Http) {}

    private _usersUrl = '/users.json';  // URL to web api


    getUsers() {
        return this.http.get(this._usersUrl)
            .map(res => <User[]> res.json().data)
            .catch(this.handleError);
    }

    private handleError (error: Response) {

        if (error.status == 401) {
            // How do I tell Angular to navigate LoginComponent from here?
        } else {
            return Observable.throw(error.json().error || 'Server error');
        }
    }
}

我的问题是:

  • 有可能吗?
  • 这是一个好习惯吗?
    • 如果是,我该如何表现?
    • 如果不是,我还能怎么做?

2 个答案:

答案 0 :(得分:11)

我的方法是创建自己的请求服务,并有一个拦截器函数,它包装了处理401和403等的实际请求。

如果您想查看它,请将其包含在下方。

ctx.on('click', function(evt){
    myChart.options.tooltips.enabled = true;
    myChart.options.scales.xAxes.display = true;
});

答案 1 :(得分:1)

我们团队的一个方向是实现API客户端类。此API客户端包装了原始的Http服务。

这个想法是,由于Http服务产生了可观察量,你可以通过将mapflatMapcatch运算符等运算符添加到Http服务生成的原始observable中来轻松扩展其行为。

我认为您会发现此示例是解决您遇到的问题的有用起点。

import { ApiRequestOptions } from './api-request-options.service';
import { Http, Response, RequestOptions, ResponseContentType } from '@angular/http';

import 'rxjs/add/observable/zip';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class ApiClient {
    // PLease note, the API request options service is a helper that we introduced
    // to generate absolute URLs based on settings in the client.
    // I did not include it here for brevity.
    constructor(private router: Router, private http: Http, private requestOptions: ApiRequestOptions) {

    }

    get<TResponse>(path: string, queryStringParams?: any): Observable<TResponse> {
        let self = this;

        return Observable.zip(
            this.requestOptions.absoluteUrlFor(path, queryStringParams),
            this.requestOptions.authorizedRequestOptions()
        ).flatMap(requestOpts => {
            let [url, options] = requestOpts;
            return self.http.get(url, options);
        }).catch(response => {
            if (response.status === 401) {
                self.router.navigate(['/login']);
            }

            return response;
        }).map((response: Response) => <TResponse>response.json());
    }

    post<TResponse>(path: string, body: any): Observable<TResponse> {
        let self = this;

        return Observable.zip(
            this.requestOptions.absoluteUrlFor(path),
            this.requestOptions.authorizedRequestOptions()
        ).flatMap(requestOpts => {
            let [url, options] = requestOpts;
            return self.http.post(url, body, options);
        }).catch(response => {
            if (response.status === 401) {
                self.router.navigate(['/login']);
            }

            return response;
        }).map((response: Response) => <TResponse>response.json());
    }

    put<TResponse>(path: string, body: any): Observable<TResponse> {
        let self = this;

        return Observable.zip(
            this.requestOptions.absoluteUrlFor(path),
            this.requestOptions.authorizedRequestOptions()
        ).flatMap(requestOpts => {
            let [url, options] = requestOpts;
            return self.http.put(url, body, options);
        }).catch(response => {
            if (response.status === 401) {
                self.router.navigate(['/login']);
            }

            return response;
        }).map((response: Response) => {
            if (response.status === 200) {
                return <TResponse>response.json();
            } else {
                return null;
            }
        });
    }

    delete(path: string): Observable<Response> {
        let self = this;

        return Observable.zip(
            this.requestOptions.absoluteUrlFor(path),
            this.requestOptions.authorizedRequestOptions()
        ).flatMap(requestOpts => {
            let [url, options] = requestOpts;
            return self.http.delete(url, options);
        }).catch(response => {
            if (response.status === 401) {
                self.router.navigate(['/login']);
            }

            return response;
        });
    }
}