[英]Unsubscribe not working when signout in angular and firebase
I'm using angular 7, firebase ( Only for authentication ) and mysql( For saving other data ). 我正在使用angular 7,firebase( 仅用于身份验证 )和mysql( 用于保存其他数据 )。 Once user signed-In successfully, a request gets data of user from mysql and saves in localStorage.
用户成功登录后,请求将从mysql获取用户数据并将其保存在localStorage中。 When I sign-out, its signing-out, but again the request (
this.userService.findByUsername(res.user.uid).subscribe(....)
) sends and gets back the data and store in the localstorage. 当我注销时,它会注销,但是请求(
this.userService.findByUsername(res.user.uid).subscribe(....)
)会再次发送并获取数据并存储在localstorage中。 I unsubscribe when sign-out. 我在退出时退订。 But it doesn't work.
但这是行不通的。 (Few other varibles and methods are removed in following codes to make it simpler)
(以下代码中删除了其他一些变量和方法,以使其更简单)
export class AuthService {
private subscription: Subscription = new Subscription();
user: Observable<firebase.User>;
private currentUserSubject: BehaviorSubject<User | null>;
authState: any = null;
constructor(private firebaseAuth: AngularFireAuth, private router: Router, private userService:UserService) {
this.user = firebaseAuth.authState;
this.subscription.add(this.firebaseAuth.authState.subscribe((auth) => {
this.authState = auth;
//getting the user object if he already signed-in
this.currentUserSubject = new BehaviorSubject<User>(localStorage.getItem('currentUser') | null);
this.currentUser = this.currentUserSubject.asObservable();
}))
signin(email: string, password: string) {
return new Promise<any>((resolve, reject) => {
// --- login with email and password in firebase
this.firebaseAuth.auth.signInWithEmailAndPassword(email, password)
.then(
res => {
// --- Once login is successful, get the user object form the backend
this.subscription =this.userService.findByUsername(res.user.uid).subscribe(data=>{
this.currentUserSubject.next(data);
localStorage.setItem("currentUser", JSON.stringify(data));
resolve(this.firebaseAuth.auth.currentUser);
})
} ,
err => {reject(err); }
).catch(err => {
console.log('Something went wrong:', err.message);
});
});
}
async logout() {
await this.firebaseAuth.auth.signOut().then(()=>{
this.currentUserSubject.next(null);
this.currentUserSubject.complete();
this.subscription.unsubscribe()
localStorage.removeItem('currentUser');
this.router.navigate(['/signin']);
})
}
}
尝试按以下方式使用first()
运算符,以确保只有一个值可以通过订阅实现。
this.userService.findByUsername(res.user.uid).pipe(first()).subscribe(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.