我有一个身份验证代码,该代码调用另一个服务的checkAuthorization
身份验证,似乎无法读取该属性。
checkAuthorization代码在httpservice.ts文件中
AuthService.Ts
@Injectable()
export class AuthService {
constructor(private httpService: HttpService) {
}
public isAuthenticated(): boolean {
let isAuthorized: boolean;
const access_token = sessionStorage.getItem('access_token');
this.httpService.checkAuthorization().subscribe(response => {
isAuthorized = response;
});
return isAuthorized;
}
httpservice.ts
public checkAuthorization(): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Cache-Control': 'no-cache, no-store, must-revalidate, post-check=0, pre-check=0',
'Pragma': 'no-cache',
'Expires': '0'
})
};
return this.http.post<any>(
this.apiUrl + ApiEndpoints.API_ENDPOINT_CONSTANTS.AUTHORIZATION, httpOptions)
.pipe(map(data => this.handleResponse(data), catchError(this.handleError)));
}
handleResponse(res: any) {
return res;
}
public handleError(error: any) {
return Observable.throw(error || 'Server Error');
}
测试文件:Authservice.spec.ts
describe('Service: AuthService', () => {
let service: AuthService;
let fixture: ComponentFixture<AuthService>;
let httpservice: HttpService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[
HttpClientTestingModule
],
providers: [
AuthService,
HttpService,
// DataMappingService,
SessionStorageService,
GoogleAnalyticsEventsService,
//{ provide: HttpClient, useValue: httpservice }
]
});
}));
fit('should return true from isAuthenticated when there is a token',() => {
let mockResponse : boolean=true;
localStorage.setItem('access_token','1234');
httpservice.checkAuthorization();
expect(service.isAuthenticated).toBe(mockResponse);
// spyOn(window.sessionStorage, 'getItem').and.returnValue('1234');
// spyOn(httpservice,'checkAuthorization').and.returnValue(mockResponse);
});
我不断收到错误消息:TypeError:无法读取属性'checkAuthorization'
未定义