TypeError: you specified an invalid object in which the stream was expected. You can provide Observed, Promising, Array or Iterable

I try to execute map from a service call, but I get an error. Looked subscription is not defined in angular 2? , and he said that in order to subscribe, we need to return from within the operators. I also have return statements.

Here is 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 
+30
angular typescript observable rxjs
source share
10 answers

In your code example, you have a map statement that receives two callbacks when it should receive only one. You can move the error handling code to your catch callback.

 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 also need to import the catch and throw statements.

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

EDIT: Note that returning Observable.throw to your catch handler will not actually catch the error - it will still appear on the console.

+14
source share

In my case, the error occurred only during the e2e tests. This was caused by throwError in my AuthenticationInterceptor.

I imported it from the wrong source because I used the import function of WebStorm. I am using RxJS 6.2.

Wrong:

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

Correct:

 import { throwError } from 'rjxs'; 

Here is the complete interceptor code:

 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); }) ); } } 
+12
source share

You return an Observable where, when your code returns only a boolean value. Therefore you need to use as below

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

If you use another common checkservice in your case, you can simply use

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

This will make your checkLogin() function with return type as void

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

and you can use this.checkService to check your status

+7
source share

If your function expects 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); }) )} 
+3
source share

I ran into this problem when trying to authenticate a user using a JSON web token. in my case this is due to an authentication interceptor.

Sending a request for user authentication should not provide a token, since it does not yet exist.

Make sure your interceptor includes this:

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

And what do you provide {'No-Auth':'True'} for your header request as follows:

  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}); } 
+1
source share

May be caused by a random comma ( , ) in the RxJS pipe(...) channel

Compilation will not catch this extra comma at the end:

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

It becomes an "invisible" undefined operator that obfuscates the entire channel and leads to a very confusing error message, which in this case has nothing to do with my real logic.

0
source share

I wrote this because I came here in search of the same mistake, and it may come in handy for someone in the future.

I get the same error when trying to initialize a service variable from its constructor by calling the remote API via http.get and .subscribe ()

After many tests, not understanding what the problem was, I finally realized: my application had authentication and HttpInterceptor, and I tried to initialize the service that calls the public API method using http.get (...) without 'No-Auth Headlines. I added them as here, and the problem is 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 :(

0
source share

In my case, in Angular-5, the service file was not imported, from which I accessed the method and signed the data. After importing the service file, it worked fine.

0
source share

I forgot to return another observable in pipe(switchMap(

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

I have the same error message when I ran my unit test and throwing an observed exception after mocking my services.

I resolved it by passing the exact function and format inside Observable.throw .

The actual code that calls the service and subscribe to receive data. note that catch handles error 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; }); 

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; }); } 

Device testing

I made fun of SomeService and return the observed data and its fine, because it has all the necessary methods.

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

The above code is okey, but when I tried to check the catch / error condition by passing Observable.throw({}) , it showed me an error since it was expecting a Response type to return from the service.

So below mocking service return gave me this error.

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

So, I fixed it by replicating the exact expected function in my return object, rather passing a value of type 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 
-one
source share

All Articles