Отображение имени пользователя после успешного входа в систему без обновления div в Angular 8 - PullRequest
0 голосов
/ 18 января 2020

Я пытаюсь показать имя пользователя, вошедшего в систему, в заголовке панели навигации после успешного входа, но по какой-то причине он отказывается появляться в панели навигации. Приложение находится в Angular 8. Журнал консоли выводит его правильно.

Пока код выглядит так:

- компонент входа

Login(user) {
this.submitted = true;
if (this.userForm.invalid) {
  return;
}

const userData = {username : this.userForm.get('username').value, password: this.userForm.get('password').value};
this.authService.authenticate(userData).subscribe((result) => {
if (result) {
if (result.msg === 'ERROR:LOGIN_FAILED') {
  this.authFailed = true;
  } else {
   this.authFailed = false;
   this.router.navigate(['dashboard']);
   this.authService.saveUserDetailsToLocalStorage(result);
   this.authService.setUserLoggedInStatus(result);

 }
} else {
 console.log('ERROR:LOGIN_FAILED');
}
}, (err) => {
 console.log(err);
});
}

- заголовок. html

 <div>Logged in as  {{ userName}}</div>

- компонент заголовка

export class HeaderComponent implements OnInit {
  isLoggedIn = false;
  subscription: Subscription;
  emitterService: any;
  userName: any;


constructor(
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService) {

  this.authenticationService.getUserLoggedInStatus().subscribe((customObject) => {
  this.userName =  customObject['user_name'];
 });

}

- служба аутентификации

export class AuthenticationService extends BaseApiService {



 @Output() loggedInUser: EventEmitter<any> = new EventEmitter<any>();

constructor(
 private router: Router,
 httpClient: HttpClient) {
 super(httpClient);
}

authenticate (user): Observable<any> {
 return this.http.post<any>(endpoint + 'login', user, httpOptions).pipe(
  catchError(this.handleError<any>('authentication'))
);
}

saveUserDetailsToLocalStorage(user){
 localStorage.setItem('user', JSON.stringify(user));
 this.loggedInUser.emit(user);
}


 getUserLoggedInStatus(): Observable<any> {
//console.log('returning' + this.loggedInUser);
  return this.loggedInUser.asObservable();
}

setUserLoggedInStatus(message: any) {
// this.loggedInUser.next(message);
 this.loggedInUser.emit(message);
}

1 Ответ

1 голос
/ 18 января 2020

Я бы предложил поработать с OnInit, который является git Angular хуком, который вы можете импортировать из @angular/core, а затем расширить свой компонент для его использования (я вижу, что он уже сделан).

Вместо того, чтобы делать подписку на конструкторе, попробуйте сделать ее там.

Кроме того, отладьте значение, полученное из запроса, с помощью некоторой записи в консоли. Всегда хорошо быть уверенным.

export class HeaderComponent implements OnInit {
  isLoggedIn = false;
  subscription: Subscription;
  emitterService: any;
  userName: any;

  constructor(
     private route: ActivatedRoute,
     private router: Router,
     private authenticationService: AuthenticationService) {}

  ngOnInit() {
     this.authenticationService.getUserLoggedInStatus()
        .subscribe((customObject) => {
            // Make sure the desired value DOES EXIST!
            console.log(customObject['user_name']);
            this.userName =  customObject['user_name'];
        });
  }

}

Не берите в голову , если приведенный выше код обеспечивает корректный вывод, но не обновляет представление - возможно, оно скрыто! С помощью инструментов разработчика убедитесь, что дерево представлений соответствует требованиям.

...