Estoy tratando de map desde una llamada de servicio, pero obtengo un error. ¿Miró la suscripción no está definida en angular 2? y decía que para suscribirnos necesitamos volver desde dentro de los operadores. También tengo declaraciones de devolución.
Aquí está mi código:
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; }); }Registro de errores:
TypeError: proporcionó un objeto no válido donde se esperaba una transmisión. Puede proporcionar un Observable, Promise, Array o Iterable
En mi caso, el error ocurrió solo durante las pruebas de e2e. Fue causado por throwError en mi AuthenticationInterceptor.
Lo importé de una fuente incorrecta porque usé la función de importación de WebStorm. Estoy usando RxJS 6.2.
Equivocado:
import { throwError } from 'rxjs/internal/observable/throwError';Correcto:
import { throwError } from 'rxjs';Aquí el código completo del 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); }) ); } }En su código de ejemplo, su operador de map recibe dos devoluciones de llamada, cuando solo debería recibir una. Puede mover su código de manejo de errores a su devolución de llamada 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); }) } También deberá importar los operadores de catch y throw .
import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; EDITAR: tenga en cuenta que al devolver Observable.throw en su controlador de captura, en realidad no capturará el error; seguirá apareciendo en la consola.
Si su función espera devolver un booleano, simplemente haga esto:
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); }) )}