After making some modifications to my Angular 2 application, I encountered a situation where something started functioning properly sooner than I expected. This has left me puzzled about why it's working in its current state. Specifically, I have an authentication service responsible for managing my login authentication. Both my login component and chat component have their own instances of the authentication service in their constructors. My intention was to pass the username from the login process to the chat view in order to display the logged-in user's username in the chatbox. Surprisingly, I was able to achieve this by adding "this.authenticationService.username = this.model.username;" in the login.component instead of the authentication.service. This has left me perplexed as to how the chat.component is able to access that information without directly importing the login component. If I remove that specific line of code from my login.component, the username does not get propagated to the chat.component. Can someone assist me in unraveling this mystery? Here are the relevant files for reference. First, my authentication.service file:
import { ContextMenu } from './../ui/context-menu.component';
import { Router, RouterLinkActive } from '@angular/router';
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthenticationService {
username;
constructor(private http: Http) {}
login(username: string, password: string) {
return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
isAuthenticated() {
if (localStorage.getItem('currentUser')) {
return true;
} else {
return false;
}
}
logout() {
localStorage.removeItem('currentUser');
console.log('User successfully logged out');
}
}
Next, my login.component file:
import { UserService } from './../../data/user.service';
import { AuthenticationService } from './../../data/authentication.service';
import { AlertService } from './../../data/alert.service';
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: 'app/views/login/login.component.html',
styleUrls: ['app/views/login/login.component.css']
})
export class LoginComponent implements OnInit {
model: any = {};
loading = false;
username;
password;
constructor(
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService,
private userService: UserService) { }
ngOnInit() {
this.authenticationService.logout();
}
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.router.navigate(['/']);
console.log('User logged in as: ' + this.model.username);
},
error => {
this.alertService.error(error);
this.loading = false;
});
this.authenticationService.username = this.model.username;
}
}
Lastly, my chat.component file:
import { AuthenticationService } from './../../data/authentication.service';
import { Router, ActivatedRoute } from '@angular/router';
import { ChatService } from './chat.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { TabPage } from '../../ui/tab-navigation/tab-page';
@Component({
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.less'],
})
export class ChatComponent extends TabPage implements OnInit, OnDestroy {
messages = [];
users = [];
routes;
connection;
userbase;
route;
message;
user;
constructor(private chatService:ChatService,
router: Router,
route: ActivatedRoute,
private authenticationService: AuthenticationService) {
super(router, route);
this._title = 'Chat Room';
}
sendMessage() {
this.chatService.sendMessage(this.message);
this.message = '';
}
sendUser() {
this.chatService.sendUser(this.user);
this.user = '';
}
trackUser() {
this.chatService.trackUser(this.route);
console.log('A user just navigated to ' + this.route);
}
eventHandler(event: KeyboardEvent): void {
if (event.key === 'Enter') {
this.chatService.sendMessage(this.message);
this.message = '';
}
}
ngOnInit() {
this.connection = this.chatService.getMessages().subscribe(message => {
this.messages.push(message);
});
this.userbase = this.chatService.getUsers().subscribe(user => {
this.users.push(user);
});
this.routes = this.chatService.getRoutes().subscribe(route => {
this.routes.push(route);
});
}
ngOnDestroy() {
this.connection.unsubscribe();
this.userbase.unsubscribe();
}
public getTabId(params): string {
return 'Chat Room';
}
}
And my chat.component.html file where the username is displayed in the chat:
<div class="centered-display" align="center">
<h3>User: {{authenticationService.username}}</h3>
<div *ngFor="let message of messages" class="message">
{{authenticationService.username}}: {{message.text}}
</div>
<input class="form-group" [(ngModel)]="message" (keypress)="eventHandler($event)">
<div class="spacing">
<button class="submit-btn" md-button (click)="sendMessage()">SEND</button>
</div>
</div>
I would appreciate any insights on why this functionality is working unexpectedly. The inclusion of "this.authenticationService.username = this.model.username;" in the login.component login function seems to be the key to this behavior. However, the chat component does not directly import the login component, so the mechanism behind this working is unclear to me.