Hey there, I'm facing an unusual issue with event emitters not functioning correctly during page refreshes.
Here's the scenario: First, the user lands on the login page. Upon successful login, they are directed to the home page where I need specific data to be displayed in header.component.html fetched from home.component.ts
The components involved are:
app.component.html
<app-layout-header></app-layout-header>
<router-outlet></router-outlet>
<app-layout-footer></app-layout-footer>
header.components.ts
@Component({
selector: "app-layout-header",
providers: [],
templateUrl: "./header.component.html"
})
export class HeaderComponent implements OnInit {
profile = {};
constructor(
private _authService: AuthService,
private _clipboardService: ClipboardService
) {}
ngOnInit() {
this._clipboardService.myProfileDataEvent.subscribe(data => {
this.profile = data;
console.log("data changes");
});
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
this._clipboardService.myProfileDataEvent.unsubscribe();
}
logout() {
this._authService.logout();
}
}
clipboard.service.ts
@Injectable()
export class ClipboardService {
@Output() myProfileDataEvent: EventEmitter<any> = new EventEmitter();
constructor() {
this.myProfileDataEvent.emit({Name:'Siraj'})
}
setProfileData(data: any) {
console.log("emitting events");
return this.myProfileDataEvent.emit(data);
}
}
In home.component.ts, I am making an API call and updating the profile data by calling
this._clipboardService.setProfileData(response.json().payload.Profile)
home.component.ts
ngOnInit() {
this._authService.checkLogin();
this._profileService.getHomeData()
.subscribe(response => {
this._clipboardService.setProfileData(response.json().payload.Profile)
},
err => {
alert('home data error');
});
}
Everything works fine if I navigate to the home page after logging in. However, if I refresh the page after logging in, the emitted event is not received in header.component.ts
Any assistance would be highly appreciated. Thank you!