简体   繁体   English

订阅/可观察到的抛出错误-Angular2 +

[英]Throwing error from subscription/observable - Angular2+

我试图从观察到的函数中抛出错误,以便可以访问订阅的err部分,但似乎无法理解该部分。

I'm not sure how to do it via the map way, but here is a different way: 我不确定如何通过地图方式进行操作,但是这是另一种方式:

import { Observable, of, throwError } from 'rxjs';

  ngOnInit() {
    this.getObs().subscribe(data => {
      console.log(data);
    }, err => {
      console.log(err);
    });
  }

  getObs() {    
    const observable = of(6);
    const isError = true;
    if (isError) {
      return throwError("Is an error!");
    }
    return observable;
  }

Working example: https://stackblitz.com/edit/angular-mqp4qv?file=src/app/app.component.ts 工作示例: https : //stackblitz.com/edit/angular-mqp4qv?file=src/app/app.component.ts

Couple ways I would handle this. 我将通过几种方式来处理此问题。 Heres one way using _throw 继承人使用_throw的一种方法

// auth.ts
import { _throw } from 'rxjs/observable/throw';

login( username, password ) {

    const body = this.jsonifyData( username, password );

    return this.http.post<any>( this.apiBaseUrl + '/auth', body )
        .pipe(
        map( res => {
            if ( 'token' in res ) {
                return res.token;
            }
            // Unsuccessful login returns error
            return _throw( res ); // from import {_throw} from 'rxjs/observable/throw';
        } )

    );
}

The other would be to just catch the error in the login component 另一种是只是在登录组件中捕获错误

I think in your component's test spec you need to mock up your authService and the login procedure. 我认为在组件的测试规范中,您需要模拟authServicelogin过程。 This mock does not make http call, just throw an error via throwError(new Error('Either username or password were incorrect')) immediately if, say, password does not match some predefined value. 该模拟不会进行http调用,只是在密码不匹配某些预定义值的情况下立即通过throwError(new Error('Either username or password were incorrect'))引发错误。 Here is some example of how to test component-http service stuff, it is a bit outdated but still actual conceptually. 是一些有关如何测试component-http服务的示例,虽然有些过时,但从概念上讲仍然是实际的。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM