我有一个下面 interceptor auth-interceptor.service.ts
import {Injectable, Injector} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Cookie} from './cookie.service';
import {Router} from '@angular/router';
import {UserService} from './user.service';
import {ToasterService} from '../toaster/toaster.service';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
private handleError(err: HttpErrorResponse): Observable<any> {
let errorMsg;
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
errorMsg = `An error occurred: ${err.error.message}`;
} …Run Code Online (Sandbox Code Playgroud) jasmine typescript angular-http-interceptors angular angular-httpclient
我目前正在转向Angular 4.3的新HttpClient.一个优点是我可以在GET方法上指定类型信息,并将返回的JSON解析为给定类型,例如
this.http.get<Person> (url).subscribe(...)
Run Code Online (Sandbox Code Playgroud)
但不幸的是,JSON中的所有日期都在结果对象中被解析为数字(可能是因为Java Date对象在后端被序列化为数字).
使用旧的Http我在调用JSON.parse()时使用了reviver函数:
this.http.get(url)
.map(response => JSON.parse(response.text(), this.reviver))
Run Code Online (Sandbox Code Playgroud)
在reviver函数中,我从数字中创建了日期对象:
reviver (key, value): any {
if (value !== null && (key === 'created' || key === 'modified'))
return new Date(value);
return value;
}
Run Code Online (Sandbox Code Playgroud)
新的HttpClient是否有类似的机制?或者在解析JSON时进行转换的最佳做法是什么?
在 Angular 中,我们使用 HttpClient 进行 HTTP 调用,该调用返回可观察值,如果我们想使用 Promise,我们可以使用lastValueFrom/firstValueFrom.
假设我们有:
async getLast() {
const get$ = this.http.get(url);
const res1 = await lastValueFrom(get$);
}
async getFirst() {
const get$ = this.http.get(url);
const res2 = await firstValueFrom(get$);
}
Run Code Online (Sandbox Code Playgroud)
res1 和 res2 总是相等吗?正确使用的版本是什么?
我正在尝试学习如何使用HttpInterceptor为应用程序对API执行的每个HTTP请求添加几个标头.我有这个拦截器:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
console.log('Intercepted HTTP call', authReq);
return next.handle(authReq);
}
}
Run Code Online (Sandbox Code Playgroud)
}
除了'Content-Type'标题之外,我还需要添加'Authorization',但我不知道怎么做(Angular HttpHeaders的文档只是方法列表,没有任何解释).
我该怎么做?谢谢!
我可以在内部使用诺言HttpInterceptor吗?例如:
export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
.then((data)=>{
//do something with data and then
return next.handle(req);
});
}
Run Code Online (Sandbox Code Playgroud)
为什么我需要这个?因为我需要在向服务器发出请求之前获取一个令牌以添加到请求标头.
我的拦截器:
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
console.log('Intercepted!');
// return next.handle(req);
this.authService.getToken()
.then((token)=>{
console.log(token);
const reqClone = req.clone({
headers: req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json')
});
console.log(reqClone);
return next.handle(reqClone);
})
.catch((err)=>{
console.log('error in interceptor' + err);
return null;
});
}
}
Run Code Online (Sandbox Code Playgroud)
请求:
this.http.post(this.baseURL + 'hero', data)
.subscribe(
(res: …Run Code Online (Sandbox Code Playgroud) rxjs es6-promise angular angular-httpclient angular-httpclient-interceptors
当我尝试HttpClient在外部库中实例化服务,然后在Angular应用程序中使用该库时,我收到StaticInjectorError错误:
使用Angular 5.0.0:
AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error:
StaticInjectorError[InjectionToken DocumentToken]:
StaticInjectorError[InjectionToken DocumentToken]:
NullInjectorError: No provider for InjectionToken DocumentToken!
at _NullInjector.get (core.js:993)
at resolveToken (core.js:1281)
at tryResolveToken (core.js:1223)
at StaticInjector.get (core.js:1094)
at resolveToken (core.js:1281)
at tryResolveToken (core.js:1223)
at StaticInjector.get (core.js:1094)
at resolveNgModuleDep (core.js:10878)
at _createClass (core.js:10919)
at _createProviderInstance$1 (core.js:10889)
Run Code Online (Sandbox Code Playgroud)
使用Angular 5.2.0-rc.0:
ERROR Error: StaticInjectorError(AppModule)[HttpXsrfTokenExtractor ->
InjectionToken DocumentToken]: StaticInjectorError(Platform:
core)[HttpXsrfTokenExtractor -> InjectionToken DocumentToken]:
NullInjectorError: No provider for InjectionToken DocumentToken!
at _NullInjector.get (core.js:994)
at resolveToken (core.js:1292) …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Angular中发出请求,我知道HTTP响应不是JSON而是文本.但是,Angular似乎期待JSON响应,因为错误如下:
SyntaxError:XMLHttpRequest.c中JSON.parse()位置0的JSON中的意外标记<
以及
解析http:// localhost:9时出现 Http失败...
这是post方法:
return this.http.post(this.loginUrl, this.createLoginFormData(username, password), this.httpOptions)
.pipe(
tap( // Log the result or error
data => console.log(data);
error => console.log(error)
)
);
Run Code Online (Sandbox Code Playgroud)
和标题.
private httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html, application/xhtml+xml, */*',
'Content-Type': 'application/x-www-form-urlencoded',
responseType: 'text'
},
) };
Run Code Online (Sandbox Code Playgroud)
我认为这responseType: 'text'足以让Angular期望非JSON响应.
祝你圣诞快乐.
我的Angular 4应用程序不会等待.
我希望在我调用API之前放慢速度.
但我只是继续撞墙.
我在我的代码中使用了HttpInterceptor.
但是这些Observable只会爆炸.
不要太鄙视.
下面你会发现我的尝试.
export class ApiUrlInterceptor implements HttpInterceptor {
constructor(private http: Http) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return Observable.create(observer => {
setTimeout(() => {
observer.next(true); //Not sure why I do this
const start = Date.now();
console.log(`Request for ${req.url}`);
return next.handle(req).do(event => {
if (event.type == HttpEventType.Response) {
const elapsed = Date.now() - start;
console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
}
});
}, 1000);
});
}
}
Run Code Online (Sandbox Code Playgroud)
结果是调用了API.
但没有安装调用者的结果
我的Observable似乎陷入困境.
我运气不好
我很清楚这是Angular中的反模式"不要等待随机数",而是构建你的应用程序,这样你就不需要了.我的实际用例是, …
wait rxjs angular-http-interceptors angular angular-httpclient
使用HttpClient时,我在返回类型上遇到编译错误.在我的函数中GetPortfolio,我期望GET调用返回类型的json对象,Observable<Portfolio>但是它给出了错误:
类型Observable<HttpEvent<Portfolio>>不能分配给类型Observable<Portfolio>.类型HttpEvent<Portfolio>不能分配给类型Portfolio.类型HttpProgressEvent不能分配给类型Portfolio.属性name缺少类型HttpProgressEvent.
我的代码:
import { Injectable } from '@angular/core';
import { environment } from './environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
export interface Portfolio {
name: string;
id: string;
}
@Injectable()
export class PortfolioService {
private httpOptions;
apiUrl: string;
constructor(private http: HttpClient) {
this.apiUrl = environment.apiUrl + "/api/portfolios";
this.httpOptions = { …Run Code Online (Sandbox Code Playgroud) 我需要从我的后端下载一个excel,它返回一个文件.
当我提出请求时,我收到错误:
TypeError:您提供了"undefined",其中包含了一个流.您可以提供Observable,Promise,Array或Iterable.
我的代码是:
this.http.get(`${environment.apiUrl}/...`)
.subscribe(response => this.downloadFile(response, "application/ms-excel"));
Run Code Online (Sandbox Code Playgroud)
我试过get和map(...)但是没有用.
细节:角度5.2
引用:
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';
Run Code Online (Sandbox Code Playgroud)
内容 - 响应类型:
Content-Type: application/ms-excel
Run Code Online (Sandbox Code Playgroud)
怎么了?
angular ×10
rxjs ×3
typescript ×3
angular-http ×1
angular-httpclient-interceptors ×1
blob ×1
date ×1
es6-promise ×1
file ×1
jasmine ×1
json ×1
observable ×1
wait ×1