gpt4 book ai didi

Angular 2 拦截器无法正常工作

转载 作者:可可西里 更新时间:2023-11-01 17:27:01 24 4
gpt4 key购买 nike

我正在尝试创建一个自定义 http 类,它扩展 Http 以像 Angular 2 上的 AngularJS 拦截器一样工作。我关注了其他 Stackoverflow 问题和一些教程,但我总是遇到相同的错误,但我找不到解决方案。

我有以下 Http 拦截器:

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
options = new RequestOptions();
let headers = new Headers();
headers.append('X-Auth-Token', 'Bearer ' + localStorage.getItem('access-token'));
options.headers = headers;
return super.request(url, options);
}
}

然后我将它添加到 app.module 中,如下所示:

  providers: [{
provide: Http,
useFactory: loadCustomHttp,
deps: [XHRBackend, RequestOptions]
}],

export function loadCustomHttp(backend: XHRBackend, defaultOptions: RequestOptions) {
return new CustomHttp(backend, defaultOptions);
}

我没有收到此配置的任何错误,但是当我发出任何请求时,我收到 401,因为未添加身份验证 header 。示例请求可以是:

import { Http } from '@angular/http';

getExample() {
let url = this.urlBase + '/test';

return this.http.get(url);
}

任何帮助将不胜感激,提前致谢:)

最佳答案

url 可以是两种不同类型之一,string 或 Request,所以

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('access-token');

if (token) {
if (typeof url === 'string') {
if (!options) {
options = { headers: new Headers() };
}
options.headers.set('Authorization', `Bearer ${token}`);
console.log('Url is string', options.headers.get('Authorization'));
} else {
url.headers.set('Authorization', `Bearer ${token}`);
console.log('Url is Request', url.headers.get('Authorization'));
}
}

return super.request(url, options);
}

关于Angular 2 拦截器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297694/

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