문제

I want to create Logout Functionality in Angular 5. The logout function will contain following pseudo code:

  1. Clear local storage authentication JWT token
  2. Redirect to login page

My question is; where should the above code be; In a component or in a service?

I believe, a service should contain logic which interacts with backend only and component should contain presentation logic (Correct me if I am wrong).

As the logout code isn't any logic dealing with backend, it should ideally sit in a component. But, if I have to perform the same operation of the logout somewhere else, it will be easier to call the service and execute the code rather than writing the same two lines again in some different component.

So where should the code really be?

도움이 되었습니까?

해결책

The documentation is pretty explicit about that: https://angular.io/guide/architecture-services

A component should not need to define things like how to fetch data from the server, validate user input, or log directly to the console. Instead, it can delegate such tasks to services. By defining that kind of processing task in an injectable service class, you make it available to any component. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.

According to that, it is fine, even encouraged to encapsulate your non-networking related logic into services too.

So, yes, you should put your logout logic into a service and call it from the components.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top