出于某种原因,互联网缺乏关于如何在Angular 4中使用的示例(它使用TypeScript,它不允许您跳过包括选项属性,如它转换成的JavaScript)。
我试图点击我的团队的RESTful API,这需要一个带有GET请求的身份验证令牌,例如:
return this.http.get(this.BASE_URL + '/api/posts/unseen/all', {
headers : {
"Authorization": 'Token token="' + TokenService.getToken() + '"'
}
})
其中TokenService
是我写的业务服务类,返回令牌以便在应用中使用。打字后,我得到了这个错误:
我出现的服务文件中的依赖项是:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Post } from '../models/post'; // business class
import 'rxjs/';
import { User } from '../models/user'; // business class
import { HttpService } from './http.service'; // service for connecting us to the base location of the endpoints. provides BASE_URL to any service that extends it
import { TokenService } from './token.service'; // token provider
注意:我尝试复制并粘贴该错误,但Visual Studio Code不会与我合作。
答案 0 :(得分:7)
使用新的httpClient可以更轻松地发送令牌。首先,您必须定义一个拦截器
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
您必须将拦截器添加到您的提供者:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from 'token.interceptor';
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]
})
export class AppModule {}
现在,当您发出任何请求时,令牌将自动出现在标题中。
import { HttpClient } from '@angular/common/http';
// ...
export class AppComponent {
constructor(public http: HttpClient) {}
public connectServer() {
this.http.get('url')
.subscribe(
data => console.log(data),
err => console.log(err)
);
}
}
在拦截器中,我使用服务来检查令牌是否有效。这不是强制性的,因为您可以定义自己的authenticationService
。但是你可以使用这个:
import { Injectable } from '@angular/core';
import decode from 'jwt-decode';
@Injectable()
export class AuthService {
public getToken(): string {
return localStorage.getItem('token');
}
public isAuthenticated(): boolean {
// get the token
const token = this.getToken();
// return a boolean indicating whether or not the token is expired
return tokenNotExpired(token);
}
}