我的应用程序有3层服务。
UserService
- 调用HttpClient
为用户执行CRUD功能HttpClient
- 用于验证/刷新令牌的服务是必要的,然后拨打AuthHttp
。AuthHttp
- 用于进行http调用并在Authorization标头中附加令牌的服务我遇到的问题是UserService
尝试使用.map(res => res.json()
映射通话的响应,但收到错误,指出res.json is not a function
。
以下是我的服务的代码。我只会发布" HTTP Get"相关的简洁方法:
user.service.ts
import { Observable } from 'rxjs/Observable';
import { environment } from '../../environments/environment';
import { HttpClient } from './http-client';
import { AddDeleteUserModel } from './AddUserModel';
@Injectable()
export class UserService {
baseApiUrl = environment.api_endpoint;
constructor(private httpClient: HttpClient) { }
getAllUsers()
{
return this.httpClient.get(this.baseApiUrl + 'users').map(res => res.json());
}
}
http.client.ts:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../environments/environment';
import { AuthHttp } from './authhttp.service';
import { AuthUserService } from './authuser.service';
import { OAuthService } from 'angular-oauth2-oidc';
@Injectable()
export class HttpClient {
constructor(
private authHttp: AuthHttp,
private authUserService: AuthUserService,
private oAuthService : OAuthService,
private router: Router
) { }
get(endpoint: string) {
if (!this.oAuthService.hasValidAccessToken)
{
this.authUserService.tokenIsBeingRefreshed.next(true);
this.oAuthService.refreshToken().then(() =>
{
this.successfulTokenRefresh();
}).catch(() =>
{
this.failedTokenRefresh();
return Observable.throw("Unable to refresh token.");
});
}
if (this.oAuthService.hasValidAccessToken)
{
return this.getInternal(endpoint);
}
}
successfulTokenRefresh() {
this.authUserService.tokenIsBeingRefreshed.next(false);
this.authUserService.requireLoginSubject.next(false);
}
failedTokenRefresh() {
this.authUserService.tokenIsBeingRefreshed.next(false);
this.authUserService.requireLoginSubject.next(false);
this.router.navigate(['/sessiontimeout']);
}
private getInternal(endpoint: string) {
console.log("Getting " + endpoint);
return this.authHttp.get(endpoint);
}
}
authhttp.ts:
import {Injectable, EventEmitter} from '@angular/core';
import {Http, Headers, RequestOptions, RequestOptionsArgs, Response, RequestMethod, Request, Connection, ConnectionBackend} from '@angular/http';
import * as Rx from 'rxjs';
export enum Action { QueryStart, QueryStop };
@Injectable()
export class AuthHttp {
process: EventEmitter<any> = new EventEmitter<any>();
authFailed: EventEmitter<any> = new EventEmitter<any>();
constructor(private _http: Http) { }
private _buildAuthHeader(): string {
return "Bearer " + sessionStorage.getItem("access_token");
}
public get(url: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Get, url, null, options);
}
public post(url: string, body: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Post, url, body, options);
}
public put(url: string, body: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Put, url, body, options);
}
public delete(url: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Delete, url, null, options);
}
public patch(url: string, body: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Patch, url, body, options);
}
public head(url: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Head, url, null, options);
}
private _request(method: RequestMethod, url: string, body?: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
let requestOptions = new RequestOptions(Object.assign({
method: method,
url: url,
body: body
}, options));
if (!requestOptions.headers) {
requestOptions.headers = new Headers();
}
requestOptions.headers.set("Authorization", this._buildAuthHeader())
return Rx.Observable.create((observer) => {
this.process.next(Action.QueryStart);
this._http.request(new Request(requestOptions))
.map(res=> res.json())
.finally(() => {
this.process.next(Action.QueryStop);
})
.subscribe(
(res) => {
observer.next(res);
observer.complete();
},
(err) => {
switch (err.status) {
case 401:
//intercept 401
this.authFailed.next(err);
observer.error(err);
break;
default:
observer.error(err);
break;
}
})
})
}
}
答案 0 :(得分:0)
过去我遇到过类似的问题。虽然我没有阅读整个代码,但我怀疑是因为您没有从Response
明确导入@angular/http
。我认为由于某种原因,它猜测错误的类型没有.json()
。
在user.service.ts
:
import { Response } from '@angular/http`;
还要将其添加到http.client.ts。
使您的http客户端签名具体:
get(endpoint: string): Response {