I am new to Angular and I am using angular 7. I have a variable userEmail
with the default value of "unknown" in a shared service pagedoctorService
. After successful login, the variable updates with logged in Email. I have imported this service in other components but when accessing userEmail
from other components, it shows the default value (unknown).
Here is what I done:
app.module.ts
...
import { PagedoctorService } from './services/pagedoctor.service';
...
...
providers: [PagedoctorService],
...
pagedoctor.service.ts
import { Injectable } from '@angular/core';
import { OktaAuthService } from '@okta/okta-angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PagedoctorService {
private accessToken;
private headers;
public userFullname: string= 'unknown';
public userEmail: string= 'unknown';
constructor(private oktaAuth: OktaAuthService, private http: HttpClient) {
this.init();
}
async init() {
this.accessToken = await this.oktaAuth.getAccessToken();
this.headers = new HttpHeaders({
Authorization: 'Bearer ' + this.accessToken
});
}
...
login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart} from '@angular/router';
import { PagedoctorService } from '../../services/pagedoctor.service';
...
constructor(private pdService: PagedoctorService){}
ngOnInit() {
...
//After successful login attempt using Okta
this.pdService.userEmail = res.user.profile.login;
console.log(this.pdService.userEmail); //This shows that email is set correctly
this.signIn.loginRedirect('/urlform');
}
urlform.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { PagedoctorService } from '../../services/pagedoctor.service';
...
...
constructor(private pdService: PagedoctorService) {
console.log(this.pdService.userEmail); // <== This shows *unknown*
Sounds like I am working with a fresh version of the service while I have provided it in module level. I am not really sure what I am missing here. Thanks in advance for your cooperation.