我是Angular的新手。
我正在开发一些与promise一起运行异步的身份验证函数,并在此代码的中间执行一些操作。 考虑到异步,我相信函数应该返回一个Observable。但是如何返回Observable以及promise的结果/错误?
authentication.service.ts
loginwithProvider(): <????> {
this.auth.signInWithPopup(provider)
.then( result =>{
/* do some things, such as getting data and logging */
})
.catch( (error) => {
/* receive the error of the provider, do some things, such as logging */
})
return ????? <---- I want to return result and errors of the provider in an Observable to the caller function
}
login.component.ts
onLogin(){
this.request = this.authenticationService.loginWithProvider().subscribe(
(data) => {
console.log("onlogin - then success");
this.router.navigate(['/']);
},
(error) => {
console.log(" onlogin - error ", error);
show_error_to_user(error); <---- error from loginWithProvider
});
}
答案 0 :(得分:0)
我找到了一种使用ReplaySubject的方法 (从Lars Bilde视频中了解到,https://www.youtube.com/watch?v=mdD2sy7r7Mk)
authentication.services.ts
loginWithProvider() : ReplaySubject<any> {
let resultSubject = new ReplaySubject(1);
var provider = new firebase.auth.FacebookAuthProvider();
this.afAuth.auth.signInWithPopup(provider)
.then( result => {
/* do some things, such as getting data and logging */
console.log("result", result)
resultSubject.next(result);
// return result;
}).catch( (error) => {
/* receive the error of the provider, do some things, such as logging */
console.log("error", error)
resultSubject.error(error);
})
return resultSubject;
}
和
login.component.ts
onlogin() {
this.authenticationService.loginWithProvider()
.subscribe(
(data) => {
console.log("onloginwithprovider - then success", data);
this.router.navigate(['/']);
},
(error) => {
console.log(" onloginwithprovider - error ", error)
});
}