Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

typescript - Angular 2 - Whats the best way to store global variables like authentication token so all classes have access to them?

Angular 2 question only:

Whats the best way to store global variables like authentication token or base url (environment settings) so that all classes can have access to them without loosing them on refresh?

So when I login I will give the user a auth token and normally store it in the $rootscope for angular 1.x.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well to create really global scope data you should register your classobjectvalue during the app bootstrapping as dependency parameter to the bootstrap function

bootstrap(MyApp,[MyGlobalService]);

This will register your service MyGlobalService (infact it can be a object or factory function or your own provider) at the root level. This dependency now can be injected into any component.

Unlike Angular1 there are multiple Injectors available for an Angular2 app, with one-to-one mapping between components and injectors. Each component has its own injector.

The Angular developer guide has some good example of such registrations. See the guide on Dependency Injection.

The other option has already been highlighted by @Yaniv.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...