加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:17:45 所属栏目:安全 来源:网络整理
导读:在我的服务中,我想描述在未经授权的情况下重定向用户时的行为. export class MessagesService { constructor (private http: Http) {} private _usersUrl = '/users.json'; // URL to web api getUsers() { return this.http.get(this._usersUrl) .map(res =
在我的服务中,我想描述在未经授权的情况下重定向用户时的行为.
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');
        }
    }
}

我的问题是:

>甚至可能吗?
>这是一个好习惯吗?

>如果是,我该怎么做?
>如果不是,我怎么能这样做?

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

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

import {Injectable} from "@angular/core"
import {Subscription,Observable} from "rxjs"
import {TokenModel} from "../../models/token.model"
import {TokenService} from "../authentication/token.service"
import {Http,Headers,URLSearchParams,RequestOptions,Request,RequestMethod} from "@angular/http"
import {Router} from "@angular/router"

@Injectable()
export class RequestService
{
    private baseUrl: string;
    private subscription: Subscription;
    private token: TokenModel;

    constructor(public tokenService: TokenService,public http: Http,public router: Router)
    {
        this.baseUrl = `${process.env.API_URL}/example`;
        this.subscription = this.tokenService.token$.subscribe(token => this.token = token);
    }

    get(path: string,params?: Object,withCredentials?: boolean): Observable<any>
    {
        this.checkAuthorised();

        const url: string = this.baseUrl + path;
        const headers: Headers = new Headers({
            'Accept': 'application/json'
        });

        const searchParams = new URLSearchParams(`user_session=${this.token.token}`);

        for (let param in params) searchParams.set(param,params[param]);

        const options: RequestOptions = new RequestOptions({
            url: url,method: RequestMethod.Get,headers: headers,search: searchParams,withCredentials: withCredentials
        });

        const request = new Request(options);

        return this.makeRequest(request);
    }

    post(path: string,body?: Object,useDataProperty?: boolean,withCredentials?: boolean): Observable<any>
    {
        this.checkAuthorised();

        const url: string = this.baseUrl + path;

        const headers: Headers = new Headers({
            'Accept': 'application/json','Content-Type': 'application/json',});

        const data = JSON.stringify(useDataProperty ? {data: body} : body);

        const searchParams = new URLSearchParams(`user_session=${this.token.token}`);

        for (let param in params) searchParams.set(param,method: RequestMethod.Post,body: data,withCredentials: withCredentials
        });

        const request = new Request(options);

        return this.makeRequest(request);
    }

    makeRequest(request: Request)
    {
        return this.intercept(this.http.request(request).map(res => res.json()));
    }

    intercept(observable: Observable<any>)
    {
        return observable.catch(err =>
        {

            if (err.status === 401)
            {
                return this.unauthorised();

            } else if (err.status === 403)
            {
                return this.forbidden();
            } else
            {
                return Observable.throw(err);
            }
        });
    }

    unauthorised(): Observable<any>
    {
        this.tokenService.clear();
        this.router.navigate(['/login']);
        return Observable.empty();
    }

    forbidden(): Observable<any>
    {
        this.router.navigate(['/']);
        return Observable.empty();
    }

    checkAuthorised(): void
    {
        if (!this.token.token.length)
        {
            this.router.navigate(['login']);
        }
    }


}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读