Angular 11 您在预期流的位置提供了“未定义”
Posted
技术标签:
【中文标题】Angular 11 您在预期流的位置提供了“未定义”【英文标题】:Angular 11 You provided 'undefined' where a stream was expected 【发布时间】:2022-01-17 18:59:36 【问题描述】:当它来自 Angular 的服务器端时,我没有收到错误消息和错误代码。
下面是我用于所有服务的代码。
我正在使用 angular 11 并且在下面的代码中出现错误
postEvidenceFiles(path: string, data: any, _arguments?: HttpParams)
let headers = new HttpHeaders();
headers = headers.set(
'Authorization',
`Bearer $this.AuthStorageService.getToken()`,
);
headers.append('Accept', 'application/json, text/plain,');
const options =
headers,
;
return this.intercept(
this.http
.post<any>(path, data, options)
.pipe(catchError(this.handleError)),
);
拦截:
intercept(observable: Observable<Response>): Observable<Response>
this.pendingRequests++;
/* NProgress.start(); */
return observable.pipe(
tap(
() =>
// Do nothing
,
(error) =>
if (error?.status == 401)
// Redirect to login page
// console.log(error)
this.router.navigate(['/login'],
queryParams: return_url: this.router.url ,
);
,
),
finalize(() =>
this.pendingRequests--;
if (this.pendingRequests <= 0)
/* NProgress.done(); */
),
);
并处理错误:
handleError(error: HttpErrorResponse)
// console.log(error);
if (error.error instanceof ErrorEvent)
// A client-side or network error occurred. Handle it accordingly.
// console.error('An error occurred:', error.error.message);
return throwError(error.error.message);
else
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
// console.error(
// `Backend returned code $error.status, ` +
// `body was: $error.error`
// );
return throwError(error.error);
请查看并告诉我我在这方面哪里出错了。
【问题讨论】:
【参考方案1】:为什么不使用 HttpInterceptor 服务
import Injectable from '@angular/core';
import HttpInterceptor, HttpEvent, HttpResponse, HttpRequest, HttpHandler from '@angular/common/http';
import Observable from 'rxjs';
@Injectable()
export class MyInterceptor implements HttpInterceptor
intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
//your logic
httpRequest = httpRequest.clone(
headers: httpRequest.headers.set("Bearer", 'TOKEN'),
);
return next.handle(httpRequest);
【讨论】:
以上是关于Angular 11 您在预期流的位置提供了“未定义”的主要内容,如果未能解决你的问题,请参考以下文章
Angular5:TypeError:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable
Angular:为组件字段提供对服务功能的引用并从模板调用它无法按预期工作