Answer the question
In order to leave comments, you need to log in
Angular2: how to update header.component on login?
How to subscribe to the header update during authorization? There are a million questions on the Internet about this, but too special cases and answers for my understanding. I'm weak.
There is user.service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class UserService {
constructor(private http: HttpClient) { }
getUser() {
return this.http.get('/server/api/userService');
}
public isAuthenticated(): Observable<boolean> {
return this.getUser().pipe(
map(data => !!data['login'])
);
}
}
import { Component, OnInit } from '@angular/core';
import { UserService } from '../../shared/user.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
providers: [UserService]
})
export class HeaderComponent implements OnInit {
user: any;
auth: boolean = false;
isAuthenticated: boolean;
constructor(private userService: UserService) { }
ngOnInit() {
this.userService.getUser().subscribe(data => {
this.user = data;
if(this.user.login !== false) {this.auth = true;}
});
this.userService.isAuthenticated().subscribe( value => {
this.isAuthenticated = value;
});
}
}
Answer the question
In order to leave comments, you need to log in
@Injectable()
export class UserService {
isAuthenticated$ = new ReplaySubject(1);
constructor(private http: HttpClient) { }
getUser() {
return this.http.get('/server/api/userService').pipe(
tap(data => this.isAuthenticated$.next(!!data['login'])),
);
}
}
export class HeaderComponent implements OnInit {
user$: Observable<User>;
isAuthenticated$: Observable<boolean>;
constructor(private userService: UserService) { }
ngOnInit() {
this.user$ = this.userService.getUser();
this.isAuthenticated$ = this.userService.isAuthenticated$;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question