简体   繁体   中英

how use service with angularjs 1.5

in angular2 a service is a class that I inject in my component.

in angularjs should I create a file javascript that contain a class as a service and then I export it ?? after that I inject it in my controller to have access to my functions ??

for example this is my LoginComponent

let LoginComponent = {
  restrict : 'E',
  template,
  controller
};
export default LoginComponent;

I need to add service as I'm adding controller ? or the service is injected one time by application if some one can provide me an example thank you

I found this it is correct ?

class MyService {
  constructor() {
    this.name = 'My Service Name'
    this.purpose = 'For demo only'
  }
  sayHello(name) {
    return 'Hello, ' + this.name
  }
}

angular.module('app', [])
  .service('MyService', MyService)

add user by module and inject it in every controller I need it ?

Yes that is the correct way of doing it.

class MyService {
  constructor() {
    this.name = 'My Service Name'
    this.purpose = 'For demo only'
  }
  sayHello(name) {
    return 'Hello, ' + this.name
  }
}

angular.module('app', [])
       .service('MyService', MyService);

Now you can write your service logic like this:

function MyService() {
   this.myService= function(broadcast) {
     //code here
   };

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