我可以在内部使用诺言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
我正在开发一个 Angular 10 应用程序,该应用程序使用HttpInterceptor向所有响应添加特定标头。不幸的是,在尝试测试此拦截器时,我不断收到以下错误:
Error: Expected one matching request for criteria "Match by function: ", found none.
Run Code Online (Sandbox Code Playgroud)
或类似的变体:
Error: Expected one matching request for criteria "Match URL: /endpoint", found none.
Run Code Online (Sandbox Code Playgroud)
我的期望是这个测试会通过,但我现在不知道为什么它不起作用。
这是我的拦截器:
Error: Expected one matching request for criteria "Match by function: ", found none.
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
Error: Expected one matching request for criteria "Match URL: /endpoint", found none.
Run Code Online (Sandbox Code Playgroud)
也就是说,可能值得指出的是,我尝试应用以下资源中的解决方案但无济于事(大多数似乎与我已经拥有的类似,而且许多似乎适用于旧版本的 Angular):
HttpClient我所知道的。testing typescript angular angular-httpclient angular-httpclient-interceptors
我正在通过课程学习角度,目前我正在学习拦截器。课程中的角度版本不是 17,但我在本地使用的版本是。因此,在第一次尝试通过类实现拦截器之后,由于拦截没有发生,因此无法正常工作。
当我查看 net 并发现我们可以设置一个拦截常量并且我们可以在 app.config.ts 中提供它时,即使这样做之后它也不起作用。所以我真的被困住了。任何帮助,将不胜感激。这是我的文件:
应用程序组件.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { Post } from './Post';
import { PostService } from './post-service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, HttpClientModule, FormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit, OnDestroy …Run Code Online (Sandbox Code Playgroud) angular ×3
angular-httpclient-interceptors ×3
angular-http ×1
es6-promise ×1
rxjs ×1
testing ×1
typescript ×1