Organizing Services for Improved Dependency Injection in Angular
Explore best practices for structuring services in Angular to streamline dependency injection and improve code organization.
0 likes
41 views
Rule Content
{ "title": "Organizing Services for Improved Dependency Injection in Angular", "description": "Explore best practices for structuring services in Angular to streamline dependency injection and improve code organization.", "category": "Angular Cursor Rules", "rules": [ { "id": "angular-service-structure", "level": "warning", "message": "Consider organizing services into feature-specific modules to enhance modularity and maintainability.", "pattern": ".*", "condition": { "type": "file", "path": ".*\\.service\\.ts$" }, "fix": { "description": "Refactor services into dedicated feature modules to improve code organization and facilitate dependency injection." } }, { "id": "angular-provided-in-root", "level": "info", "message": "Use 'providedIn: \"root\"' in service decorators to ensure singleton instances and enable tree-shaking.", "pattern": "@Injectable\\(\\{[^}]*\\}\\)", "condition": { "type": "file", "path": ".*\\.service\\.ts$" }, "fix": { "description": "Add 'providedIn: \"root\"' to the @Injectable decorator to optimize service instantiation and application performance." } }, { "id": "angular-avoid-component-providers", "level": "warning", "message": "Avoid providing services at the component level unless a unique instance is required.", "pattern": "providers:\\s*\\[.*\\]", "condition": { "type": "file", "path": ".*\\.component\\.ts$" }, "fix": { "description": "Remove the 'providers' array from the component decorator to prevent multiple instances of the service." } }, { "id": "angular-injectable-decorator", "level": "error", "message": "Ensure all services are decorated with @Injectable to enable dependency injection.", "pattern": "export\\s+class\\s+\\w+Service\\s*\\{", "condition": { "type": "file", "path": ".*\\.service\\.ts$" }, "fix": { "description": "Add the @Injectable decorator to the service class to make it available for dependency injection." } }, { "id": "angular-injection-token", "level": "info", "message": "Use InjectionToken for non-class dependencies to ensure type safety and uniqueness.", "pattern": ".*", "condition": { "type": "file", "path": ".*\\.service\\.ts$" }, "fix": { "description": "Define an InjectionToken for the non-class dependency and use it in the service constructor." } } ] }