Error Response in Console in Chrome 我是新来的角度拦截器。我正在使用Asp。 Net Core Web Api用于通信数据库。当我通过拦截器从Angular 7向Web Api发布请求时,我遇到了问题。该请求转到服务并执行,但返回“给我错误”。哪一个 “您在期望流的位置提供了'undefined'。您可以提供Observable,Promise,Array或Iterable。”我无法理解它是来自API还是来自拦截器。以下是我的拦截器代码。我还要附加API代码。
import {Injectable, Injector} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders, HttpErrorResponse, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent, HttpResponse, HttpUserEvent} from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable, BehaviorSubject, throwError } from 'rxjs';
import {map, tap, catchError, switchMap, finalize, filter, take, retry} from "rxjs/operators";
import { AuthorizationService } from '../Services/BasicServices/authorization.service';
import { AccountService } from '../Services/BasicServices/account.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor
{
isRefreshingToken: boolean = false;
tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);
public whiteList=[
{
"url":"/api/account/ldap-auth",
"requirAuth":false
},
{
"url":"assets/",
"requirAuth":false
}
];
constructor(private authService: AuthorizationService,private regService:AccountService,private router:Router,private _accountService:AccountService ){}
addToken(req: HttpRequest<any>, itoken: string): HttpRequest<any>
{
return req.clone({ setHeaders: { Authorization: 'Bearer ' + itoken }});
}
intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | any>
{
if(this.whiteList.some((item)=>request.url.indexOf(item.url)>-1))
{
debugger;
return next.handle(request);
}
return next.handle(this.addTokenToRequest(request, this.authService.GetAuthData().auth_token))
.pipe(
catchError(err =>
{
if (err instanceof HttpErrorResponse) {
//console.log("Error Status : " + (<HttpErrorResponse>err).status);
switch ((<HttpErrorResponse>err).status) {
case 401:
console.log("not auth!!!!!!!!!!!!!!");
return this.handle401Error(request, next);
case 400:
//return this.handle401Error(request, next);
return <any>this.authService.LogOut();
}
} else {
return throwError(err);
}
}));
}
private addTokenToRequest(request: HttpRequest<any>, token: string) : HttpRequest<any> {
return request.clone({
headers: request.headers
.set('Authorization', `Bearer ${token}`)
.set('Cache-Control', 'no-cache')
.set('Pragma', 'no-cache')
.set('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT')
.set('If-Modified-Since', '0')
});
//return request.clone({ setHeaders: { Authorization: `Bearer ${token}`} });
}
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if(!this.isRefreshingToken) {
this.isRefreshingToken = true;
// Reset here so that the following requests wait until the token
// comes back from the refreshToken call.
this.tokenSubject.next(null);
return this._accountService.RefreshToken().pipe(
switchMap(data=>{
if(data)
{
console.log("-----------------refreshed--------------");
// alert(JSON.stringify(data));
this.authService.SetAuthData(data);
return next.handle(this.addTokenToRequest(request, data.auth_token));
}
return <any>this.authService.LogOut();
}),
catchError(err=>{
return <any>this.authService.LogOut();
}),
finalize(()=>{
this.isRefreshingToken = false;
})
)
}
else
{
this.isRefreshingToken = false;
return this.tokenSubject
.pipe(filter(token => token != null),
take(1),
switchMap(token => {
return next.handle(this.addTokenToRequest(request, token));
}));
}
}
}
这也是Angular服务代码,用于通过拦截器将请求从Angular发送到API
UpdateUserRoles(userId, Role,SelecteduserName):Observable<any>
{
debugger
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
var body={
"userid":userId,
"Role":Role,
"UserName":SelecteduserName
}
return this.http.post<any>(this._url + "api/updateUserRoles", body);
};
API代码在这里
public async Task<IActionResult> updateUserRoles(AddRole role)
{
var response = await _accountService.updateUserRoles(role.userid, role.Role,role.UserName);
if (response.isSuccessful)
{
return Ok(response.message);
}
else
{
return BadRequest(response.message);
}
}
AnyBody可以帮我吗,最近三天我一直被困在这里。 预先感谢