1

I would like to know if there is any way to autoinject a component in every component of my angular application.

I mean, like a "parent" component which methods can be invoked from other components without needing to use:

import { Parent } ...

I suspect this won't be possible, anyhow, is there another solution to face this problem?

If you are wondering why I need this, is becouse I have to check in every page if an element exists on the local storage.

Thank you!

4
  • Have you considered making a shared service ? Commented Jun 15, 2017 at 12:16
  • If you don't import something, you won't be able to refer to it. Whether you import a utility, which sounds like it might work in your case, or inject some service, you'll have to import the function or class or service or something. There is no way to "auto-import" values into every module, which sort of sounds like what you want. Commented Jun 15, 2017 at 12:18
  • 1
    What are you going to do if the item does or does not exist in local storage? You want this check to be made magically and transparently for every component? Commented Jun 15, 2017 at 12:29
  • Depends largely on what you do if the item is in localstorage or not. IMHO LocalStorageCheck doesn't sound like a component. Commented Jun 15, 2017 at 12:37

1 Answer 1

4

Why not create a base class that all of your component classes can extend. Then you can add the local storage check code into your bass class.

@Component({
  selector: 'mu-component',
  templateUrl: './my-component.html'
})
export class MyComponent extends LocalStorageCheckComponent {}
Sign up to request clarification or add additional context in comments.

2 Comments

IMHO it's unlikely that superclasses are the best way to just bring what (according to my understanding of the OP's question) amount to nothing more than some utilities (or a service).
Not bad idea Dean. But that would imply editing all my components to add the "extends" directive. I was wondering If could be possible an "auto" inject without the need of editing every single component of my angular app. (declaring it at app.module / app.component level may be)

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.