简体   繁体   中英

Why in Angular 2+ is it preferred to put shared variables in services rather than store them in a constant object that can be imported directly?

I am creating a SPA in Angular 7, and want to follow best practices, but I don't fully understand why everywhere recommends storing data in services rather than in a file with a constant that can be directly imported.

Directly importing the constant seems a lot simpler. Am I missing something important?

My code:

userSession.ts

export const userSession = {
    loggedIn: null,
    userId: null
};

something.service.ts :

import { userSession } from '../appGlobals/user-session';
// decorators, ect .......
export class SomethingService {  
  constructor() { }
  doSomething() {
    if (userSession.loggedIn) {
      // do something
    }
  }
}

Suggested code (to my understanding):

user.service.ts

//imports and decorator ....
export class UserService {
  session = {
    loggedIn: boolean;
    userId: number;
  }
//...
}

some.service.ts

import { UserSession } from '../services/user.service.ts';
// decorators, ect .......
export class SomeService {
  constructor(private userService: UserService) { }
  doSomething() {
    if (this.userService.session.loggedIn) {
      // do something
    }
  }
}

With large classes that use the user session fields, the code seems to be a lot cleaner if to just use "userSession" object instead of "this.userService.session" and inject the dependency into the constructor. So what are the advantages/disadvantages of each setup?

In my opinion there is no difference in the example you are describing, however most of the times these shared variables might not be prepared when a component using them is completely loaded, ie the variable might be filled after an API call. For that reason services are preferred that can incorporate proper functionalities to manipulate these shared variables in a proper and clean way. Also keep in mind that most of these shared variables are some sorts of Observable objects that can notify the components using them when the value is ready (ie applies to scenario when values are filled afterwards or are subject to changes).

One big advantage is testing.

In your code, userSession is declared outside of the class therefore it would be hard to write unit test code.

But in the suggested one, the service is injected in constructor so test code can be written with the service or even mock service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM