Home > Back-end >  How to create a global object without query from database
How to create a global object without query from database

Time:07-18

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;
    })
  }

CodePudding user response:

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'));
  • Related