【发布时间】:2019-08-10 07:00:37
【问题描述】:
我正在使用 angular,我可以看到令牌正在从后端服务器正确中继,但 angular 无法使用以下代码读取
import { IServerAuthResponse } from './auth.service';
import { CCommonUrl } from './../../shared/util/CCommonUrl';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ROLE } from './role.enum';
import { Observable, BehaviorSubject, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import * as decode from 'jwt-decode';
import { transformError } from 'src/app/shared/common/common';
export interface IAuthStatus {
isAuthenticated: boolean;
userId: number;
userRole: ROLE;
}
export interface IServerAuthResponse {
accessToken: string;
}
const defaultStatus: IAuthStatus = {
isAuthenticated: false,
userId: null,
userRole: ROLE.NONE
};
@Injectable({
providedIn: 'root'
})
export class AuthService {
public authProvider: (
username: string,
password: string
) => Observable<IServerAuthResponse>;
authStatus = new BehaviorSubject<IAuthStatus>(defaultStatus);
constructor(
private http: HttpClient
) {
this.authProvider = this.mtAuthProvider;
}
private mtAuthProvider(
username: string,
password: string
): Observable<IServerAuthResponse> {
const authorization: IServerAuthResponse = { accessToken: '' };
this.http.post<any>(CCommonUrl.LOGIN, {
username,
password
}, { observe: 'response' }).subscribe((res) => {
authorization.accessToken = res.headers.get('Authorization');
// Authorization
});
return of(authorization);
}
public login(username: string, password: string): Observable<IAuthStatus> {
const loginResponse = this.authProvider(username, password).pipe(
map(value => {
console.log('accesstoken==>', value.accessToken);
return decode(value.accessToken) as IAuthStatus;
}), catchError(transformError)
);
loginResponse.subscribe(
res => {
console.log('res', res);
this.authStatus.next(res);
}, err => {
this.logout();
return throwError(err);
}
);
return loginResponse;
}
public logout(): void {
this.authStatus.next(defaultStatus);
}
}
当我与邮递员核对时,一切正常。 请看一下
我是 Angular 的新手,我正在发布我正在使用的这段代码。它无法接收令牌,我无法弄清楚原因。
请查看它,如果我需要更改某些内容,请告诉我。
另一件事是这个 api 正在访问后端服务器。我通过服务器日志验证了自己。
【问题讨论】:
标签: typescript angular8