Is it possible to use HostListener in a Service? The 2019 Stack Overflow Developer Survey Results Are InIs it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or DirectiveHow to properly import variables and functions in angular typescript files?How can I make my Application more Scalable and Flexible using Angular 4?Custom Pure Pipe in Angular2 with change detection pushAngular2 Observable with RxJS no errors but event not firedWhy is an RxJS Subject faster than multiple event listeners?Header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight responseAngular - Is there list of HostListener-Events?I need to return a String but only have an ObservableAngular http requestError TS2355: A function whose declared type is neither 'void' nor 'any' must return a valueCreate subscription that never endsPackagr: Having trouble exporting my service that has an RXJS Subject in the service

How can I have a shield and a way of attacking with a ranged weapon at the same time?

How to translate "being like"?

Why did Peik say, "I'm not an animal"?

How can I add encounters in the Lost Mine of Phandelver campaign without giving PCs too much XP?

How much of the clove should I use when using big garlic heads?

Why can I use a list index as an indexing variable in a for loop?

Short story: child made less intelligent and less attractive

Does HR tell a hiring manager about salary negotiations?

"as much details as you can remember"

Is an up-to-date browser secure on an out-of-date OS?

RequirePermission not working

Button changing its text & action. Good or terrible?

Will it cause any balance problems to have PCs level up and gain the benefits of a long rest mid-fight?

Why didn't the Event Horizon Telescope team mention Sagittarius A*?

Did any laptop computers have a built-in 5 1/4 inch floppy drive?

Why doesn't UInt have a toDouble()?

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

Can there be female White Walkers?

What is this business jet?

How do I free up internal storage if I don't have any apps downloaded?

Are there any other methods to apply to solving simultaneous equations?

For what reasons would an animal species NOT cross a *horizontal* land bridge?

What information about me do stores get via my credit card?



Is it possible to use HostListener in a Service?



The 2019 Stack Overflow Developer Survey Results Are InIs it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or DirectiveHow to properly import variables and functions in angular typescript files?How can I make my Application more Scalable and Flexible using Angular 4?Custom Pure Pipe in Angular2 with change detection pushAngular2 Observable with RxJS no errors but event not firedWhy is an RxJS Subject faster than multiple event listeners?Header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight responseAngular - Is there list of HostListener-Events?I need to return a String but only have an ObservableAngular http requestError TS2355: A function whose declared type is neither 'void' nor 'any' must return a valueCreate subscription that never endsPackagr: Having trouble exporting my service that has an RXJS Subject in the service



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








18















I want to create a service which detects all keyboard input, translates the key strokes into actions based on a configurable mapping, and exposes observables which various elements can bind to to react to specific key presses.



The following is a simplification of my code so far, it worked when HostListener was in a component, but now I've moved it into a service it never fires even though it is definitely initialised. Is it not possible to detect input like this in a service?



import Injectable, HostListener from '@angular/core';

import Subject from 'rxjs/Subject';

@Injectable()
export class InputService

@HostListener('window:keydown', ['$event'])
keyboardInput(event: any)
console.log(event);











share|improve this question



















  • 1





    I guess it is't not possible. Use window.addEventListener instead

    – yurzui
    Sep 20 '16 at 11:41

















18















I want to create a service which detects all keyboard input, translates the key strokes into actions based on a configurable mapping, and exposes observables which various elements can bind to to react to specific key presses.



The following is a simplification of my code so far, it worked when HostListener was in a component, but now I've moved it into a service it never fires even though it is definitely initialised. Is it not possible to detect input like this in a service?



import Injectable, HostListener from '@angular/core';

import Subject from 'rxjs/Subject';

@Injectable()
export class InputService

@HostListener('window:keydown', ['$event'])
keyboardInput(event: any)
console.log(event);











share|improve this question



















  • 1





    I guess it is't not possible. Use window.addEventListener instead

    – yurzui
    Sep 20 '16 at 11:41













18












18








18


1






I want to create a service which detects all keyboard input, translates the key strokes into actions based on a configurable mapping, and exposes observables which various elements can bind to to react to specific key presses.



The following is a simplification of my code so far, it worked when HostListener was in a component, but now I've moved it into a service it never fires even though it is definitely initialised. Is it not possible to detect input like this in a service?



import Injectable, HostListener from '@angular/core';

import Subject from 'rxjs/Subject';

@Injectable()
export class InputService

@HostListener('window:keydown', ['$event'])
keyboardInput(event: any)
console.log(event);











share|improve this question
















I want to create a service which detects all keyboard input, translates the key strokes into actions based on a configurable mapping, and exposes observables which various elements can bind to to react to specific key presses.



The following is a simplification of my code so far, it worked when HostListener was in a component, but now I've moved it into a service it never fires even though it is definitely initialised. Is it not possible to detect input like this in a service?



import Injectable, HostListener from '@angular/core';

import Subject from 'rxjs/Subject';

@Injectable()
export class InputService

@HostListener('window:keydown', ['$event'])
keyboardInput(event: any)
console.log(event);








angular angular2-services






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 26 '17 at 12:10







trelltron

















asked Sep 20 '16 at 11:33









trelltrontrelltron

18918




18918







  • 1





    I guess it is't not possible. Use window.addEventListener instead

    – yurzui
    Sep 20 '16 at 11:41












  • 1





    I guess it is't not possible. Use window.addEventListener instead

    – yurzui
    Sep 20 '16 at 11:41







1




1





I guess it is't not possible. Use window.addEventListener instead

– yurzui
Sep 20 '16 at 11:41





I guess it is't not possible. Use window.addEventListener instead

– yurzui
Sep 20 '16 at 11:41












2 Answers
2






active

oldest

votes


















16














Seems like its not possible to use it in a service.



You have to use the old way window.addEventListener like @yurzui pointed already.



https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview



import Component, NgModule, HostListener, Injectable from '@angular/core'
import BrowserModule from '@angular/platform-browser'

@Injectable()
export class MyService

constructor()
window.addEventListener('keydown', (event) =>
console.dir(event);
);




@Component(
selector: 'my-app',
template: `
<div>
<h2>Hello name</h2>
</div>
`,
)
export class App

constructor(private _srvc: MyService)
this.name = 'Angular2'



@NgModule(
imports: [ BrowserModule ],
declarations: [ App ],
providers: [MyService],
bootstrap: [ App ]
)
export class AppModule





share|improve this answer























  • I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

    – trelltron
    Sep 20 '16 at 14:43












  • Beats creating a component.

    – John
    Dec 1 '16 at 12:10











  • I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

    – blueprintchris
    May 31 '18 at 14:58











  • does it work work with Universal?

    – Kuncevič
    Apr 2 at 1:27


















0














There is an other way of doing so, by using rendererFactory2 and renderer2.
I am using such a service to monitor idleness and logout the user accordingly.
Here is part of the code :



@Injectable()
export class IdleService

renderer: Renderer2;
lastInteraction: Date = new Date();
definedInactivityPeriod = 10000;

constructor(
private rendererFactory2: RendererFactory2,
private auth: AuthService,
private router: Router
)
this.renderer = this.rendererFactory2.createRenderer(null, null);
this.renderer.listen('document', 'mousemove', (evt) =>
console.log('mousemove');
this.lastInteraction = new Date();
);
// Subscribing here for demo only
this.idlePoll().subscribe();


idlePoll()
return interval(1000)
.pipe(
tap(() => console.log('here', new Date().getTime() - this.lastInteraction.getTime())),
takeWhile(() =>
if ((new Date().getTime() - this.lastInteraction.getTime()) > this.definedInactivityPeriod)
this.auth.logout();

return (new Date().getTime() - this.lastInteraction.getTime()) < this.definedInactivityPeriod;
)
);





By passing null to renderer factory this.rendererFactory2.createRenderer(null, null) you get a hold of the default DOMrenderer and can therefore listen to window events.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39592972%2fis-it-possible-to-use-hostlistener-in-a-service%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    16














    Seems like its not possible to use it in a service.



    You have to use the old way window.addEventListener like @yurzui pointed already.



    https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview



    import Component, NgModule, HostListener, Injectable from '@angular/core'
    import BrowserModule from '@angular/platform-browser'

    @Injectable()
    export class MyService

    constructor()
    window.addEventListener('keydown', (event) =>
    console.dir(event);
    );




    @Component(
    selector: 'my-app',
    template: `
    <div>
    <h2>Hello name</h2>
    </div>
    `,
    )
    export class App

    constructor(private _srvc: MyService)
    this.name = 'Angular2'



    @NgModule(
    imports: [ BrowserModule ],
    declarations: [ App ],
    providers: [MyService],
    bootstrap: [ App ]
    )
    export class AppModule





    share|improve this answer























    • I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

      – trelltron
      Sep 20 '16 at 14:43












    • Beats creating a component.

      – John
      Dec 1 '16 at 12:10











    • I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

      – blueprintchris
      May 31 '18 at 14:58











    • does it work work with Universal?

      – Kuncevič
      Apr 2 at 1:27















    16














    Seems like its not possible to use it in a service.



    You have to use the old way window.addEventListener like @yurzui pointed already.



    https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview



    import Component, NgModule, HostListener, Injectable from '@angular/core'
    import BrowserModule from '@angular/platform-browser'

    @Injectable()
    export class MyService

    constructor()
    window.addEventListener('keydown', (event) =>
    console.dir(event);
    );




    @Component(
    selector: 'my-app',
    template: `
    <div>
    <h2>Hello name</h2>
    </div>
    `,
    )
    export class App

    constructor(private _srvc: MyService)
    this.name = 'Angular2'



    @NgModule(
    imports: [ BrowserModule ],
    declarations: [ App ],
    providers: [MyService],
    bootstrap: [ App ]
    )
    export class AppModule





    share|improve this answer























    • I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

      – trelltron
      Sep 20 '16 at 14:43












    • Beats creating a component.

      – John
      Dec 1 '16 at 12:10











    • I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

      – blueprintchris
      May 31 '18 at 14:58











    • does it work work with Universal?

      – Kuncevič
      Apr 2 at 1:27













    16












    16








    16







    Seems like its not possible to use it in a service.



    You have to use the old way window.addEventListener like @yurzui pointed already.



    https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview



    import Component, NgModule, HostListener, Injectable from '@angular/core'
    import BrowserModule from '@angular/platform-browser'

    @Injectable()
    export class MyService

    constructor()
    window.addEventListener('keydown', (event) =>
    console.dir(event);
    );




    @Component(
    selector: 'my-app',
    template: `
    <div>
    <h2>Hello name</h2>
    </div>
    `,
    )
    export class App

    constructor(private _srvc: MyService)
    this.name = 'Angular2'



    @NgModule(
    imports: [ BrowserModule ],
    declarations: [ App ],
    providers: [MyService],
    bootstrap: [ App ]
    )
    export class AppModule





    share|improve this answer













    Seems like its not possible to use it in a service.



    You have to use the old way window.addEventListener like @yurzui pointed already.



    https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview



    import Component, NgModule, HostListener, Injectable from '@angular/core'
    import BrowserModule from '@angular/platform-browser'

    @Injectable()
    export class MyService

    constructor()
    window.addEventListener('keydown', (event) =>
    console.dir(event);
    );




    @Component(
    selector: 'my-app',
    template: `
    <div>
    <h2>Hello name</h2>
    </div>
    `,
    )
    export class App

    constructor(private _srvc: MyService)
    this.name = 'Angular2'



    @NgModule(
    imports: [ BrowserModule ],
    declarations: [ App ],
    providers: [MyService],
    bootstrap: [ App ]
    )
    export class AppModule






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Sep 20 '16 at 11:46









    mxiimxii

    11.4k23144




    11.4k23144












    • I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

      – trelltron
      Sep 20 '16 at 14:43












    • Beats creating a component.

      – John
      Dec 1 '16 at 12:10











    • I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

      – blueprintchris
      May 31 '18 at 14:58











    • does it work work with Universal?

      – Kuncevič
      Apr 2 at 1:27

















    • I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

      – trelltron
      Sep 20 '16 at 14:43












    • Beats creating a component.

      – John
      Dec 1 '16 at 12:10











    • I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

      – blueprintchris
      May 31 '18 at 14:58











    • does it work work with Universal?

      – Kuncevič
      Apr 2 at 1:27
















    I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

    – trelltron
    Sep 20 '16 at 14:43






    I guess this is the only way to do what I want. If I want to use HostListener I'll have to create an invisible InputHandler component and let each component configure it to emit the events they want.

    – trelltron
    Sep 20 '16 at 14:43














    Beats creating a component.

    – John
    Dec 1 '16 at 12:10





    Beats creating a component.

    – John
    Dec 1 '16 at 12:10













    I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

    – blueprintchris
    May 31 '18 at 14:58





    I did the same as this but used the 'load' event for addEventListener and it does not trigger if I navigate to the component using the router but DOES trigger if i reload the page???

    – blueprintchris
    May 31 '18 at 14:58













    does it work work with Universal?

    – Kuncevič
    Apr 2 at 1:27





    does it work work with Universal?

    – Kuncevič
    Apr 2 at 1:27













    0














    There is an other way of doing so, by using rendererFactory2 and renderer2.
    I am using such a service to monitor idleness and logout the user accordingly.
    Here is part of the code :



    @Injectable()
    export class IdleService

    renderer: Renderer2;
    lastInteraction: Date = new Date();
    definedInactivityPeriod = 10000;

    constructor(
    private rendererFactory2: RendererFactory2,
    private auth: AuthService,
    private router: Router
    )
    this.renderer = this.rendererFactory2.createRenderer(null, null);
    this.renderer.listen('document', 'mousemove', (evt) =>
    console.log('mousemove');
    this.lastInteraction = new Date();
    );
    // Subscribing here for demo only
    this.idlePoll().subscribe();


    idlePoll()
    return interval(1000)
    .pipe(
    tap(() => console.log('here', new Date().getTime() - this.lastInteraction.getTime())),
    takeWhile(() =>
    if ((new Date().getTime() - this.lastInteraction.getTime()) > this.definedInactivityPeriod)
    this.auth.logout();

    return (new Date().getTime() - this.lastInteraction.getTime()) < this.definedInactivityPeriod;
    )
    );





    By passing null to renderer factory this.rendererFactory2.createRenderer(null, null) you get a hold of the default DOMrenderer and can therefore listen to window events.






    share|improve this answer



























      0














      There is an other way of doing so, by using rendererFactory2 and renderer2.
      I am using such a service to monitor idleness and logout the user accordingly.
      Here is part of the code :



      @Injectable()
      export class IdleService

      renderer: Renderer2;
      lastInteraction: Date = new Date();
      definedInactivityPeriod = 10000;

      constructor(
      private rendererFactory2: RendererFactory2,
      private auth: AuthService,
      private router: Router
      )
      this.renderer = this.rendererFactory2.createRenderer(null, null);
      this.renderer.listen('document', 'mousemove', (evt) =>
      console.log('mousemove');
      this.lastInteraction = new Date();
      );
      // Subscribing here for demo only
      this.idlePoll().subscribe();


      idlePoll()
      return interval(1000)
      .pipe(
      tap(() => console.log('here', new Date().getTime() - this.lastInteraction.getTime())),
      takeWhile(() =>
      if ((new Date().getTime() - this.lastInteraction.getTime()) > this.definedInactivityPeriod)
      this.auth.logout();

      return (new Date().getTime() - this.lastInteraction.getTime()) < this.definedInactivityPeriod;
      )
      );





      By passing null to renderer factory this.rendererFactory2.createRenderer(null, null) you get a hold of the default DOMrenderer and can therefore listen to window events.






      share|improve this answer

























        0












        0








        0







        There is an other way of doing so, by using rendererFactory2 and renderer2.
        I am using such a service to monitor idleness and logout the user accordingly.
        Here is part of the code :



        @Injectable()
        export class IdleService

        renderer: Renderer2;
        lastInteraction: Date = new Date();
        definedInactivityPeriod = 10000;

        constructor(
        private rendererFactory2: RendererFactory2,
        private auth: AuthService,
        private router: Router
        )
        this.renderer = this.rendererFactory2.createRenderer(null, null);
        this.renderer.listen('document', 'mousemove', (evt) =>
        console.log('mousemove');
        this.lastInteraction = new Date();
        );
        // Subscribing here for demo only
        this.idlePoll().subscribe();


        idlePoll()
        return interval(1000)
        .pipe(
        tap(() => console.log('here', new Date().getTime() - this.lastInteraction.getTime())),
        takeWhile(() =>
        if ((new Date().getTime() - this.lastInteraction.getTime()) > this.definedInactivityPeriod)
        this.auth.logout();

        return (new Date().getTime() - this.lastInteraction.getTime()) < this.definedInactivityPeriod;
        )
        );





        By passing null to renderer factory this.rendererFactory2.createRenderer(null, null) you get a hold of the default DOMrenderer and can therefore listen to window events.






        share|improve this answer













        There is an other way of doing so, by using rendererFactory2 and renderer2.
        I am using such a service to monitor idleness and logout the user accordingly.
        Here is part of the code :



        @Injectable()
        export class IdleService

        renderer: Renderer2;
        lastInteraction: Date = new Date();
        definedInactivityPeriod = 10000;

        constructor(
        private rendererFactory2: RendererFactory2,
        private auth: AuthService,
        private router: Router
        )
        this.renderer = this.rendererFactory2.createRenderer(null, null);
        this.renderer.listen('document', 'mousemove', (evt) =>
        console.log('mousemove');
        this.lastInteraction = new Date();
        );
        // Subscribing here for demo only
        this.idlePoll().subscribe();


        idlePoll()
        return interval(1000)
        .pipe(
        tap(() => console.log('here', new Date().getTime() - this.lastInteraction.getTime())),
        takeWhile(() =>
        if ((new Date().getTime() - this.lastInteraction.getTime()) > this.definedInactivityPeriod)
        this.auth.logout();

        return (new Date().getTime() - this.lastInteraction.getTime()) < this.definedInactivityPeriod;
        )
        );





        By passing null to renderer factory this.rendererFactory2.createRenderer(null, null) you get a hold of the default DOMrenderer and can therefore listen to window events.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 11:13









        StanislasdrgStanislasdrg

        8171327




        8171327



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39592972%2fis-it-possible-to-use-hostlistener-in-a-service%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко