简体   繁体   English

如何从一个服务抛出错误并将其捕获到Angular2的另一个组件中

[英]How to throw errors from one service and catch it in another component in Angular2

I have used Firebase for authenticaton purpose. 我已将Firebase用于身份验证目的。

This is the code for authentication 这是验证代码

export class AuthService {

      signupUser(email:string,password:string){
        firebase.auth().createUserWithEmailAndPassword(email,password).catch((error)=>{
          console.log(error);
        })
      }

This is code for signup in signup.Component.ts 这是signup.Component.ts中用于注册的代码

onSignup(form:NgForm){
  const email=form.value.email;
  const password=form.value.password;
  this.authService.signupUser(email,password);
  }

So instead of printing an error, I would like to throw an error and catch it in signup component so that I can use that error and display a flash message to the user. 因此,我不想抛出错误,而是想抛出一个错误并将其捕获到注册组件中,以便可以使用该错误并向用户显示一条即时消息。 How can I do that? 我怎样才能做到这一点? Can somebody please solve my problem? 有人可以解决我的问题吗?

Just return the promise, and let the caller attach their own handlers: 只需返回promise,然后让调用方附加自己的处理程序即可:

signupUser(email:string,password:string){
  return firebase.auth().createUserWithEmailAndPassword(email,password);
}

Then the caller can do: 然后,呼叫者可以执行以下操作:

this.authService.signupUser(email,password).catch(...);

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

相关问题 如何通过服务将数据从Angular2中的一个组件发送到另一个组件 - How to send data from one component to another component in Angular2 through service (Angular2 / 4)使用服务将数据从一个组件发送到另一组件 - (Angular2/4) Sending data from one component to another using a service 如何从另一个组件调用一个组件中的方法是 angular2 - how to call a method in one component from another component is angular2 如何在Angular2中将值从一个组件传递到另一个组件? - How to pass value from one component to another component in Angular2? 如何在Angular2中将变量值从一个组件传递到另一个组件 - How to pass variable value from one component to another in Angular2 如何在angular2中触发从一个组件到另一个组件的功能? - How to trigger function from one component to another in angular2? 如何在angular2中将数组的索引从一个组件传递到另一个组件? - How to pass index of an array from one component to another in angular2? 如何将数据从一个组件传递到另一个 angular2 - How to Pass the data from one component to another angular2 将数值从一个组件发送到Angular2中的另一个组件 - Send a number value from one component to another component in Angular2 Angular2从另一个组件调用一个函数组件 - Angular2 call one function component from another component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM