如何解决登录后未在app.component.ts中触发订阅
我需要了解为什么成功登录后我的可观察项没有被触发,这是我到目前为止的结果:
app.component.ts
public ngOnInit(): void {
const sub = this.authService.CurrentUser.pipe(
concatMap(user => {
if(user) {
this.isAuthenticated = true;
this.service.getParticipants(user.id);
}
return throwError('Error');
}),).subscribe();
}
service.ts
public GetParticipants(id: string): Observable<Participant> {
return this.http.get<any>(`${this.baseUrl}/participant/GetParticipants?enterpriseId=${enterpriseId}`)
.pipe(
map(p => Participant.fromJsonToParticipant(p))
);
}
auth.service.ts
export class AuthService {
private currentUser = new BehaviorSubject<Participant | null>(null);
public currentUser$ = this.currentUser.asObservable();
public get CurrentUser(): Observable<Participant | null> {
return this.currentUser.asObservable();
}
constructor(private router: Router) {
const storageUser = sessionStorage.getItem('currentUser');
const userJson = storageUser ? JSON.parse(storageUser) : null;
const user = storageUser ? Participant.fromJsonToParticipant(userJson) : null;
if(user) {
this.currentUser.next(user);
}
}
public login(username: string,password: string): void {
// Login logic
sessionStorage.setItem('currentUser',JSON.stringify(participant));
this.currentUser.next(user);
}
public logout(): void {
sessionStorage.removeItem('currentUser');
this.currentUser.next(null);
}
app-routing.module.ts
const routes: Routes = [
{
path: '',pathMatch: 'full',redirectTo: 'dashboard',},{
path: 'dashboard',loadChildren: () =>
import('./dashboard/dashboard.module').then(
(m) => m.DashboardModule
),canActivate: [CanActivateAuthGuard],canLoad: [CanLoadAuthGuard],}];
@NgModule({
imports: [RouterModule.forRoot(routes)],exports: [RouterModule],})
export class AppRoutingModule {}
app.component订阅仅在启动时触发,但是在执行登录后,不会再次触发该订阅,而且我不知道为什么会发生这种情况。就像登录后订阅已关闭
解决方法
如果将concatMap更改为水龙头并消除错误会发生什么?
const sub = this.authService.CurrentUser.pipe(
tap(user => {
if(user) {
this.isAuthenticated = true;
this.service.getParticipants(user.id);
}
}),).subscribe();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。