[英]res.json is not a function on UserService call
My application has 3 tiers of services. 我的应用程序有3层服务。
UserService
- makes calls to HttpClient
to perform CRUD functions for users UserService
- 调用HttpClient
为用户执行CRUD功能 HttpClient
- a service used to validate/refresh the token is necessary, and then make a call to the AuthHttp
. HttpClient
- 用于验证/刷新令牌的服务是必要的,然后调用AuthHttp
。 AuthHttp
- a service used to make an http call and attach the token in the Authorization header AuthHttp
- 用于进行http调用并在Authorization标头中附加令牌的服务 The issue that I am running into is that the UserService
tries to map the response of the call using .map(res => res.json()
, but I receive an error stating that res.json is not a function
. 我遇到的问题是UserService
尝试使用.map(res => res.json()
来映射调用的响应,但是我收到一条错误,指出res.json is not a function
。
Here is the code for my services in order. 这是我的服务的代码。 I will only post the "HTTP Get" related methods for brevity: 为简洁起见,我只会发布“HTTP Get”相关方法:
user.service.ts 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: 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: 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;
}
})
})
}
}
I had a similar problem in the past. 我过去也遇到过类似的问题。 Though I did not read the entire code, I suspect it is because you do not explicitly import Response
from @angular/http
. 虽然我没有阅读整个代码,但我怀疑是因为你没有从@angular/http
显式导入Response
。 I think for some reason it guesses the wrong type which does not have .json()
. 我认为由于某种原因它猜测了没有.json()
的错误类型。
Add at the top of your user.service.ts
: 在user.service.ts
的顶部添加:
import { Response } from '@angular/http`;
Also add it to http.client.ts. 也将它添加到http.client.ts。
Make your http client signature specific: 使您的http客户端签名具体:
get(endpoint: string): Response {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.