简体   繁体   English

类型错误:您提供了一个预期流的无效对象。 你可以提供一个 Observable、Promise、Array 或 Iterable

[英]TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I am trying to map from a service call but getting an error.我正在尝试从服务调用进行map ,但出现错误。 Looked at subscribe is not defined in angular 2?subscribe 是不是在 angular 2 中定义的? and it said that in order to subscribe we need to return from inside the operators.它说为了订阅我们需要从运营商内部返回。 I have return statements as well.我也有退货声明。

Here's my code:这是我的代码:

checkLogin(): Observable<boolean> {
  return this.service
    .getData()
    .map(
      (response) => {
        this.data = response;
        this.checkservice = true;
        return true;
      },
      (error) => {
        // debugger;
        this.router.navigate(["newpage"]);
        console.log(error);
        return false;
      }
    )
    .catch((e) => {
      return e;
    });
}

Error log:错误日志:

TypeError: You provided an invalid object where a stream was expected.类型错误:您提供了一个预期流的无效对象。 You can provide an Observable, Promise, Array, or Iterable你可以提供一个 Observable、Promise、Array 或 Iterable

In my case the error occurred only during e2e tests.在我的情况下,错误仅在 e2e 测试期间发生。 It was caused by throwError in my AuthenticationInterceptor.这是由我的 AuthenticationInterceptor 中的throwError引起的。

I imported it from a wrong source because I used WebStorm's import feature.我从错误的来源导入它,因为我使用了 WebStorm 的导入功能。 I am using RxJS 6.2.我正在使用 RxJS 6.2。

Wrong:错误的:

import { throwError } from 'rxjs/internal/observable/throwError';

Correct:正确的:

import { throwError } from 'rxjs';

Here the full code of the interceptor:这里是拦截器的完整代码:

import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const reqWithCredentials = req.clone({withCredentials: true});
    return next.handle(reqWithCredentials)
     .pipe(
        catchError(error => {
          if (error.status === 401 || error.status === 403) {
            // handle error
          }
          return throwError(error);
        })
     );
  }
}

In your example code, you have your map operator receiving two callbacks, when it should only be receiving one.在您的示例代码中,您的map操作员接收了两个回调,而它应该只接收一个回调。 You can move your error handling code to your catch callback.您可以将错误处理代码移至 catch 回调。

checkLogin():Observable<boolean>{
    return this.service.getData()
                       .map(response => {  
                          this.data = response;                            
                          this.checkservice=true;
                          return true;
                       })
                       .catch(error => {
                          this.router.navigate(['newpage']);
                          console.log(error);
                          return Observable.throw(error);
                       })
   }

You'll need to also import the catch and throw operators.您还需要导入catchthrow运算符。

import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

EDIT: Note that by returning Observable.throw in your catch handler, you won't actually capture the error - it will still surface to the console.编辑:请注意,通过在 catch 处理程序中返回Observable.throw ,您实际上不会捕获错误 - 它仍然会出现在控制台上。

If your function is expecting to return a boolean, just do this:如果您的函数期望返回布尔值,请执行以下操作:

  1. Import:进口:
import { of, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
  1. Then然后
checkLogin(): Observable<boolean> {
  return this.service.getData()
    .pipe(
      map(response => {
        this.data = response;
        this.checkservice = true;
        return true;
      }),
      catchError(error => {
        this.router.navigate(['newpage']);
        console.log(error);
        return of(false);
      })
)}

You are returning an Observable where as your code returns just a boolean.您正在返回一个 Observable,而您的代码仅返回一个布尔值。 So you need to use as below所以你需要使用如下

.map(response => <boolean>response.json())

If you are using another common service checkservice in your case, you can simply use如果你在你的情况下使用另一个公共服务checkservice服务,你可以简单地使用

this.service.getData().subscribe(data=>console.log(data));

This will make your checkLogin() function with return type as void这将使您的checkLogin()函数的返回类型为 void

 checkLogin():void{
      this.service.getData()
            .map(response => {  
                           this.data = response;                            
                           this.checkservice=true;
             }).subscribe(data=>{ });

and you can use of this.checkService to check your condition你可以使用this.checkService来检查你的情况

I was forgetting to return the other observable in pipe(switchMap(我忘记返回pipe(switchMap(的另一个可观察对象pipe(switchMap(

this.dataService.getPerson(personId).pipe(
  switchMap(person => {
     //this.dataService.getCompany(person.companyId); // return missing
     return this.dataService.getCompany(person.companyId);
  })
)

Can be triggered by a stray comma ( , ) in an RxJS pipe(...)可以由 RxJS pipe(...)的杂散逗号 ( , ) 触发pipe(...)

The compile won't catch this extra comma at the end:编译不会在最后捕获这个额外的逗号:

pipe(first(), map(result => ({ event: 'completed', result: result}),);

It becomes an 'invisible' undefined operator which screws the whole pipe up, and leads to a very confusing error message - which in this case has nothing to do with my actual logic.它变成了一个“不可见”的undefined运算符,它将整个管道拧紧,并导致非常混乱的错误消息 - 在这种情况下与我的实际逻辑无关。

I had the same issue caused by importing the internal version of 'takeUntil' instead of the operators Change我有同样的问题,因为导入了“takeUntil”的内部版本而不是操作符 Change

import { takeUntil } from 'rxjs/internal/operators/takeUntil';

to

import { takeUntil } from 'rxjs/operators';

This happen also for other operators这也发生在其他运营商身上

I have been facing this issue when trying to authenticate a user using JSON Web Token.我在尝试使用 JSON Web Token 对用户进行身份验证时遇到了这个问题。 in my case it's related to authentication interceptor.就我而言,它与身份验证拦截器有关。

Sending a request to authenticate a user doesn't have to provide a token since it doesn't exist yet.发送对用户进行身份验证的请求不必提供令牌,因为它尚不存在。

Check that your interceptor include this:检查您的拦截器是否包含以下内容:

if (req.headers.get('No-Auth') == "True")
            return next.handle(req.clone());

And that you provide {'No-Auth':'True'} to your header's request like this:并且您向标头的请求提供{'No-Auth':'True'} ,如下所示:

  authenticateUser(user): Observable<any> {
    const headers = new HttpHeaders({'No-Auth':'True'});
    headers.append('Content-Type', 'application/json');
    return this.httpClient.post(`${this.apiEndpoint}/auth/authenticate`, user, {headers: headers});
  }

A hint for anyone experiencing this.给任何遇到这种情况的人的提示。 This can happen when a switchMap doesn't receive an observable return value (like null ).switchMap没有收到可观察的返回值(如null )时,就会发生这种情况。 Simply add a default case, so it always returns an observable.简单地添加一个默认情况,所以它总是返回一个可观察的。

        switchMap((dateRange) => {
          if (dateRange === 'Last 24 hours') {
            return $observable1;
          }
          if (dateRange === 'Last 7 Days') {
            return $observable2;
          }
          if (dateRange === 'Last 30 Days') {
            return $observable3;
          }
          // This line will work for default cases
          return $observableElse;
        })

I wrote this because I arrive here searching for the same error, and this could be useful for someone in the future.我写这篇文章是因为我来到这里寻找相同的错误,这可能对将来的某个人有用。

I get the same error while trying to initialize a service variable from its constructor making a call to a remote API trough http.get and .subscribe()我在尝试从其构造函数初始化服务变量时遇到相同的错误,通过 http.get 和.subscribe()调用远程 API

After many tests without understanding what the problem was, i finally get it: My application had authentication and an HttpInterceptor , and i was trying to initialize the service calling a public API method using http.get(...) without 'No-Auth' headers.经过多次测试但不知道问题出在哪里,我终于明白了:我的应用程序具有身份验证和HttpInterceptor ,并且我尝试使用http.get(...)初始化调用公共 API 方法的服务,而没有“No-Auth” '标题。 I added them like here, and problem solved for me:我在这里添加了它们,问题为我解决了:

getData() {
var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });    
return this.http.get(environment.urlApi.Literales, { headers: reqHeader });  
}

What a headache :(好头疼:(

就我在 Angular-5 中的情况而言,没有导入服务文件,我正在访问该方法并订阅数据。导入服务文件后,它工作正常。

this error happened with me when i am using interceptor you have to do this in your interceptor当我使用拦截器时,我发生了这个错误,您必须在拦截器中执行此操作

return next.handle(request).map(event => {
        if (event instanceof HttpResponse) {

        }
        return event;
    },
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401 || error.status === 400) {
          // some logic

        }

This error happened to me @angular 7这个错误发生在我身上@angular 7

You provided an invalid object where a stream was expected.您在需要流的地方提供了一个无效的对象。 You can provide an Observable, Promise, Array, or Iterable.您可以提供 Observable、Promise、Array 或 Iterable。

The error is actually self-explanatory, it says somewhere in the observable I pass the invalid object.该错误实际上是不言自明的,它说在 observable 的somewhere我传递了无效对象。 In my case, there was lots of API call but all the calls were failing because of wrong server configuration.就我而言,有很多 API 调用,但由于服务器配置错误,所有调用都失败了。 I tried to use map , switchMap , or other rxjs operator but the operators are getting undefined objects.我尝试使用mapswitchMap或其他 rxjs 运算符,但这些运算符正在获取未定义的对象。

So double-check your rxjs operator inputs.因此,请仔细检查您的 rxjs 操作员输入。

I was also facing the same issue when i was calling a method inside switchMap, apparently I found that if we use method inside switchMap it must return observable.当我在 switchMap 内部调用方法时,我也面临同样的问题,显然我发现如果我们在 switchMap 内部使用方法,它必须返回可观察的。

i used pipe to return observable and map to perform operations inside pipe for an api call which i was doing inside method rather than subscribing to it.我使用管道返回 observable 并映射以在管道内执行操作以进行 api 调用,这是我在方法内部执行而不是订阅它。

I've had this error when there's been different RxJS-versions across projects.当跨项目存在不同的 RxJS 版本时,我遇到了这个错误。 The internal checks in RxJS fails because there are several different Symbol_observable . RxJS 中的内部检查失败,因为有几个不同的Symbol_observable Eventually this function throws once called from a flattening operator like switchMap .最终这个函数抛出一次从像switchMap这样的扁平操作符switchMap

Try importing symbol-observable in some entry point.尝试在某个入口点导入符号可观察。

// main index.ts
import 'symbol-observable';

我不确定这是否会对任何人有所帮助,但在我的情况下,我使用了distinctUntilChanged并且在函数内部出现了一个异常,并显示了此错误消息。

You will get the following error message too when you provide undefined or so to an operator which expects an Observable , eg.当您向需要 Observable的运算符提供 undefined 左右时,您也会收到以下错误消息,例如。 takeUntil .直到.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 

In my case I mistakely imported Action into my combineEpics, rather than Epic...就我而言,我错误地将 Action 导入到我的 combineEpics 中,而不是 Epic 中...

Verify all the functions within combine Epics are epic funcitons验证组合史诗中的所有函数都是史诗函数

I had a similar error using RXJS in NESTJS.我在 NESTJS 中使用 RXJS 时遇到了类似的错误。

Error: TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. +1ms

In my case I forgot to return an Observable in a switchMap.就我而言,我忘记在 switchMap 中返回一个 Observable。 This caused that no Observable was received in the next RXJS operator or client code.这导致在下一个 RXJS 操作符或客户端代码中没有收到 Observable。

Once I returned an Observable in the switchMap, the error disappeared.一旦我在 switchMap 中返回了一个 Observable,错误就消失了。

I have the same exact error message while I was doing my unit test and throwing observable exception after mocking my services.在进行单元测试并在模拟我的服务后抛出可观察到的异常时,我有相同的错误消息。

I resolved it by passing exact function and format inside Observable.throw .我通过在Observable.throw传递精确的函数和格式来解决它。

Actual code which calls the service and subscribe to get data.调用服务并subscribe以获取数据的实际代码。 notice that catch to handle the 400 error.注意catch来处理400错误。

     this.search(event).catch((e: Response) => {
        if (e.status === 400) {
          console.log(e.json().message);
        } else if (e.url) {
          console.log('HTTP Error: ' + e.status + ' ' + e.statusText,
            'URL: ' + e.url, 'Info: ' + e.json().message));
        }
      }).finally(() => {
        this.loading = false;
      }).subscribe((bData) => {
        this.data = bData;
      });

The code inside the service服务内的代码

  search() {
    return this.someService.getData(request)
       .do((r) => {
          this.someService.defaultHeaders.delete('skipAlert');
          return r;
        })
      .map((r) => {
          return r.businessObjectDataElements.length && r.businessObjectDataElements || null;
        });
  }

Unit Testing单元测试

I have mocked the SomeService and returning observable data and its fine as it have all the required methods inside it.我已经模拟了 SomeService 并返回了可观察的数据,它很好,因为它里面有所有必需的方法。

 someServiceApi = fixture.debugElement.injector.get(SomeService);
 spyOn(someServiceApi, 'getData').and.returnValue(Observable.of({}));

The above code is okey but when when I was trying to test the catch/error condition by passing Observable.throw({}) it was showing me the error as it was expecting Response type return from the service.上面的代码很好,但是当我尝试通过传递Observable.throw({})来测试捕获/错误条件时,它向我显示了错误,因为它期望从服务返回Response类型。

So below service mocking return was giving me that error.所以下面的服务模拟返回给了我那个错误。

someServiceApi.getData
  .and.returnValue(Observable.throw(new Response({status: 400, body: [], message: 'not found error'})));

So I Corrected it by replicating the exact expected function in my return object rather passing a Response type value.所以我通过在我的返回对象中复制确切的预期函数而不是传递一个Response类型值来纠正它。

someServiceApi.getData
  .and.returnValue(Observable.throw({status: 400, json: () => { return {message: 'not found error'}}, body: []}));
// see `json: () => { return {message: 'not found error'}}` inside return value

In regard to the "You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable" error.关于“您在需要流的地方提供了无效对象。您可以提供 Observable、Promise、Array 或 Iterable”错误。

This could happen if you import { Observable } from 'rxjs' after (below) some module/function/whatever, which actually uses it.如果您(下面)某个模块/函数/任何实际使用它的模块/函数/任何东西之后import { Observable } from 'rxjs'就会发生这种情况。

Solution : move this import above the import of that module.解决方案:将此导入移动到该模块的导入上方

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular:您在需要流的地方提供了一个无效的对象。 你可以提供一个 Observable、Promise、Array 或 Iterable - Angular: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable xplat您提供了一个无效的对象,该对象应在其中流。 您可以提供一个Observable,Promise,Array或Iterable - xplat You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 类型错误:您在需要流的地方提供了“未定义”。 你可以提供一个 Observable、Promise、Array 或 Iterable - TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 错误类型错误:您在需要流的地方提供了“空”。 你可以提供一个 Observable、Promise、Array 或 Iterable - ERROR TypeError: You provided 'null' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable Angular 11 错误:您提供了无效的 object,而应为 stream。 您可以提供一个 Observable、Promise、Array 或 Iterable - Angular 11 error: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable TypeError:您在需要 stream 的地方提供了“未定义”。 部署angular时可以提供Observable、Promise、Array或Iterable - TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable when deploying angular Angular5:TypeError:您提供了&#39;undefined&#39;,其中包含一个流。 您可以提供Observable,Promise,Array或Iterable - Angular5 : TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable TypeError:您在预期 stream 的地方提供了“未定义”。 您可以提供 Observable、Promise、Array 或 Iterable。 在<jasmine></jasmine> - TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. at <Jasmine> @ngrx / effects给出了TypeError:你提供了&#39;undefined&#39;来预期流。 您可以提供Observable,Promise,Array或Iterable - @ngrx/effects gives TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 错误类型错误:您在需要流的地方提供了“未定义”。 您可以在 Angular 服务中提供 Observable、Promise、Array 或 Iterable - ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable in Angular Services
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM