首页 > 解决方案 > Angular Observer 在组件上捕获错误

问题描述

我的组件上有这个代码

  this.authService.login4(this.email, this.password)
         .pipe(first())
         .subscribe(
             data => {
                  console.log(data);

             },
             error => {
                console.log('err');

             });

以及我的服务上的这个实现:

login4(email: string, password: string): Observable<any> {
  return  this.http.post('http://localhost:3000/api' + '/login', {
    email: email,
    password: password
  });
}

如果出现错误,则会打印错误,但是如果我将登录的实现更改为此,则不会打印组件错误。这是正常的吗?我想知道组件中是否有任何错误。

  login4(email: string, password: string): Observable<any> {

return  this.http.post('http://localhost:3000/api' + '/login', {
    email: email,
    password: password
  }).pipe(
  tap(data => console.log(data)),
  catchError(this.handleError<any>(`err`))
);
}

标签: angularrxjs

解决方案


如果您发现错误,您将停止它。您可以接住并扔掉,也可以在它到达组件之前不接住。请参见下面的两个示例:

接住并扔掉。对于处理预期的错误很有用。

ngOnInit() {
    this.login().subscribe(
        res => {
            console.log(res);
        },
        err => {
            console.log(err);
        }
    );
}

login() {
    return ajax.post("http://localhost:3000/api/login").pipe(
        map(data => data),
        catchError(err => {
            throw new Error("My Error");
        })
    );
}

直到在组件中才捕获。

ngOnInit() {
    this.login().subscribe(
        res => {
            console.log(res);
        },
        err => {
            console.log(err);
        }
    );
}

login() {
    return ajax.post("http://localhost:3000/api/login").pipe(
        map(data => data)
    );
}

两者都会起作用。


推荐阅读