首页 文章

TypeError:您提供了一个无效的对象,其中包含一个流 . 您可以提供Observable,Promise,Array或Iterable

提问于
浏览
21

我正在尝试从服务电话 map 但收到错误 . 看着subscribe is not defined in angular 2?,它说为了订阅我们需要从运营商内部返回 . 我也有回复陈述 .

这是我的代码:

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

错误日志:

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

6 回答

  • 1

    如果你的函数期望返回一个布尔值,那么就这样做:

    • 导入:
    import { Observable } from 'rxjs/Observable';
    
    • 然后
    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.of(false);
               })
     }
    
  • 11

    在您的示例代码中,您的 map 运算符接收两个回调,而它应该只接收一个回调 . 您可以将错误处理代码移动到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);
                           })
       }
    

    您还需要导入 catchthrow 运算符 .

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

    EDIT: 请注意,通过在catch处理程序中返回 Observable.throw ,您实际上不会捕获错误 - 它仍然会显示在控制台上 .

  • 7

    在我的情况下,错误仅发生在e2e测试期间 . 它是由我的AuthenticationInterceptor中的 throwError 引起的 .

    我从错误的源导入它,因为我使用了WebStorm的导入功能 . 我正在使用RxJS 6.2 .

    错误:

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

    正确:

    import { throwError } from 'rjxs';
    

    这里是拦截器的完整代码:

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

    你正在返回一个Observable,你的代码只返回一个布尔值 . 所以你需要使用如下

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

    如果您正在使用其他常用服务 checkservice ,则可以使用

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

    这将使_1172474_函数的返回类型为void

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

    你可以使用 this.checkService 检查你的病情

  • 0

    尝试使用JSON Web Token对用户进行身份验证时,我一直面临这个问题 . 在我的情况下,它与身份验证拦截器有关 .

    发送对用户进行身份验证的请求不必提供令牌,因为它尚不存在 .

    检查你的拦截器包括:

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

    并且您提供 {'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});
      }
    
  • 3

    在我进行单元测试并在模拟我的服务后抛出可观察的异常时,我有完全相同的错误消息 .

    我通过在 Observable.throw 中传递确切的函数和格式来解决它 .

    调用服务的实际代码和 subscribe 获取数据 . 注意 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;
          });
    

    服务中的代码

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

    单元测试

    我已经模拟了SomeService并返回了可观察的数据,因为它里面有所有必需的方法 .

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

    上面的代码是okey但是当我试图通过传递 Observable.throw({}) 来测试捕获/错误条件时,它向我显示错误,因为它期望从服务返回 Response 类型 .

    所以在服务模拟返回下面给了我这个错误 .

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

    所以我通过复制返回对象中的确切预期函数而不是传递 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
    

相关问题