4

I have created module in Angular 4. Also i created service using @Injectable, added to module. Now my requirement is , service should not load during module loading. once i perform action or event like click, then service should load. So please help me how to implement this requirement.

thanks, Narsi p

2 Answers 2

1

You have to use injector explicitly. The injector is the one which instantiate the service.

Suppose square is the service,

class Square { name = 'square'; } 

Call the service in component using below code.

const injector = Injector.create({providers: [{provide: Square, deps: []}]}); 
const shape: Square = injector.get(Square);
expect(shape.name).toEqual('square');
expect(shape instanceof Square).toBe(true);
Sign up to request clarification or add additional context in comments.

1 Comment

create method doesn't existed in Injector class. Injector.create throwing error.
1

If you are using Angular 6 then there is a feature provided by angular itself to lazy load services by using it's new syntax.

@Injectable({
   providdedIn : 'root'
})

Using this way Service can be loaded lazy by angular behind the scene, which will remove redundant code and lead to better performance and speed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.