Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a global object without query from database

How to get a global value, I need to use a User object in each component, every time I need to query from the database, how to create a global User object, without needing to query from the database every time

export class WorkReportComponent {

  user: User = new User();

  constructor(private weekService: WeekService,
              private nzNotificationService: NzNotificationService,
              private router: Router) {
   
    this.weekService.getUserBack().subscribe(data => {
      this.user = data;
    })
  }
export class WeekService {
 
  serviceURL = "http://localhost:8080"

  constructor(private http: HttpClient) {
   
  }


  getUserBack() {
    return this.http.get<User>(this.serviceURL + "/user/" + 1002, httpOptions);
  }

export class WorkDetailComponent {

  user: User = new User();

  constructor(private weekService: WeekService,
              private nzNotificationService: NzNotificationService,
              private router: Router) {
   
    this.weekService.getUserBack().subscribe(data => {
      this.user = data;
    })
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can save it in your localstorage because if you try to save it in a variable, and when DOM refreshes, then your user object will be gone.

// Suppose this is your user object
user = {
    name: "Jim Brown",
  age: 32,
  country: "Singapore",
  isActive: true
}

// Save it in your localstorage by stringify it
localStorage.setItem('user', JSON.stringify(user));

// To retrieve it and use it as normal object you need to parse it
JSON.parse(localStorage.getItem('user'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading