简体   繁体   中英

How to use services or factories in angularjs

I am new to angularjs and i am currently working on a dummy shopping website project for practice. I am a little confused about how to link the app.js with the files present in other modules.

I am working on a login module which has its own LoginController and LoginService in their respective folders inside the loginmodule.

In the LoginService I have defined two properties ie isLogged and username. when the user is successfully logged in using the $http.post() method(through the user table in database) the values are changed to true and username respectively.

How can I make sure that the loginService is available throughout the website accross different modules so that the user remains logged in.

Thanks in advance.

You don't need to make each section into its own module. You can use one module for your entire application. So instead of call angular.module('newModuleName', []) for each item, you would call angular.module('app') (without the []), and it would continue adding new components onto your single application.

The other option is to create new modules like angular.module('loginModule', []) , and then you add it as a dependency into your app, like angular.module('app', ['loginModule']) . From this point, any service/factory in your loginModule app will now be available for $injection within your app .

But generally, you may want to refrain from making separate modules for each section, unless that module acts like a "plugin" that is completely distinct and separate from the rest (ie. doesn't depend on anything within app to function). If you need two-way dependency, like app needs to make calls to login , but login needs to also make calls to app , it should all be within the same application.

You should also look at OAuth2 authentication and JSON Web Tokens (JWT) for the correct way to do authorization within AngularJS.

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