I am trying to map
from a service call but getting an error.
Looked at subscribe is not defined in angular 2? and it said that in order to subscribe we need to
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
}
I've had this error when there's been different RxJS-versions across projects. The internal checks in RxJS fails because there are several different Symbol_observable
. Eventually this function throws once called from a flattening operator like switchMap
.
Try importing symbol-observable in some entry point.
// main index.ts
import 'symbol-observable';
You are returning an Observable where as your code returns just a boolean. 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
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 of this.checkService
to check your condition
,
) in an RxJS 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.
If your function is expecting to return a boolean, just do this:
import { of, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
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);
})
)}
In your example code, you have your map
operator receiving two callbacks, when it should only be receiving one. You can move your 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'll need to also import the catch
and throw
operators.
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.