V
V
Vadimqa2020-01-11 15:27:14
Angular
Vadimqa, 2020-01-11 15:27:14

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'])
      );
    }

}

And header.component
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;
        });
    
    }

}

The fact is that the header template does not react in any way until the entire application is reloaded, some kind of subscription is needed to change the data, but I don’t understand anything about it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-01-11
@Xuxicheta

@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$;
     }
}

When using AsyncPipe, this is sufficient, although even isAuthenticated is superfluous.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question