gpt4 book ai didi

typescript - Angular 2 : how to redirect if API returns an error?

转载 作者:太空狗 更新时间:2023-10-29 17:17:50 25 4
gpt4 key购买 nike

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

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, params?: 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, params[param]);

const options: RequestOptions = new RequestOptions({
url: url,
method: RequestMethod.Post,
headers: headers,
body: data,
search: searchParams,
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']);
}
}


}

关于typescript - Angular 2 : how to redirect if API returns an error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com