Call a compnent from a service










0















I have 2 component that need to communicate, and a service in the middle.



Service



import Injectable from '@angular/core';
import Subject from 'rxjs/Subject';

@Injectable()
export class CommunicationService

// Observable string sources
private onOpen = new Subject<any>();

// Observable string streams
onOpen = this.onOpen.asObservable();

// Service message commands
callComponentMethod()
this.onOpen.next();





Component A



 import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp1',
template: `
<button type="button" (click)="callMethod()">Call method from Component1</button>
`
)
export class Component1

constructor( private communicationService: CommunicationService )

callMethod = function ()
this.communicationService.onOpen();





Component B



import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp2',
template: ``
)
export class Component2

constructor( private communicationService: CommunicationService )

this.communicationService.onOpen.subscribe(
() =>
alert('(Component2) onOpen');

);






following this plunker : http://plnkr.co/edit/SmntWy0GTNdvGB5Jb3hO?p=preview the method are called but, I would like to pass a parameter. how do I do this ?










share|improve this question

















  • 1





    May be you can pass parameter in stream : callComponentMethod(params) this.onOpen.next(params);

    – junk
    Nov 14 '18 at 6:27











  • angularfirebase.com/lessons/…

    – Hoax
    Nov 14 '18 at 6:29











  • Which param you want to pass?

    – User3250
    Nov 14 '18 at 6:34











  • depends of where, right now I wish a custom typed object

    – Bobby
    Nov 14 '18 at 6:46















0















I have 2 component that need to communicate, and a service in the middle.



Service



import Injectable from '@angular/core';
import Subject from 'rxjs/Subject';

@Injectable()
export class CommunicationService

// Observable string sources
private onOpen = new Subject<any>();

// Observable string streams
onOpen = this.onOpen.asObservable();

// Service message commands
callComponentMethod()
this.onOpen.next();





Component A



 import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp1',
template: `
<button type="button" (click)="callMethod()">Call method from Component1</button>
`
)
export class Component1

constructor( private communicationService: CommunicationService )

callMethod = function ()
this.communicationService.onOpen();





Component B



import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp2',
template: ``
)
export class Component2

constructor( private communicationService: CommunicationService )

this.communicationService.onOpen.subscribe(
() =>
alert('(Component2) onOpen');

);






following this plunker : http://plnkr.co/edit/SmntWy0GTNdvGB5Jb3hO?p=preview the method are called but, I would like to pass a parameter. how do I do this ?










share|improve this question

















  • 1





    May be you can pass parameter in stream : callComponentMethod(params) this.onOpen.next(params);

    – junk
    Nov 14 '18 at 6:27











  • angularfirebase.com/lessons/…

    – Hoax
    Nov 14 '18 at 6:29











  • Which param you want to pass?

    – User3250
    Nov 14 '18 at 6:34











  • depends of where, right now I wish a custom typed object

    – Bobby
    Nov 14 '18 at 6:46













0












0








0


0






I have 2 component that need to communicate, and a service in the middle.



Service



import Injectable from '@angular/core';
import Subject from 'rxjs/Subject';

@Injectable()
export class CommunicationService

// Observable string sources
private onOpen = new Subject<any>();

// Observable string streams
onOpen = this.onOpen.asObservable();

// Service message commands
callComponentMethod()
this.onOpen.next();





Component A



 import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp1',
template: `
<button type="button" (click)="callMethod()">Call method from Component1</button>
`
)
export class Component1

constructor( private communicationService: CommunicationService )

callMethod = function ()
this.communicationService.onOpen();





Component B



import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp2',
template: ``
)
export class Component2

constructor( private communicationService: CommunicationService )

this.communicationService.onOpen.subscribe(
() =>
alert('(Component2) onOpen');

);






following this plunker : http://plnkr.co/edit/SmntWy0GTNdvGB5Jb3hO?p=preview the method are called but, I would like to pass a parameter. how do I do this ?










share|improve this question














I have 2 component that need to communicate, and a service in the middle.



Service



import Injectable from '@angular/core';
import Subject from 'rxjs/Subject';

@Injectable()
export class CommunicationService

// Observable string sources
private onOpen = new Subject<any>();

// Observable string streams
onOpen = this.onOpen.asObservable();

// Service message commands
callComponentMethod()
this.onOpen.next();





Component A



 import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp1',
template: `
<button type="button" (click)="callMethod()">Call method from Component1</button>
`
)
export class Component1

constructor( private communicationService: CommunicationService )

callMethod = function ()
this.communicationService.onOpen();





Component B



import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp2',
template: ``
)
export class Component2

constructor( private communicationService: CommunicationService )

this.communicationService.onOpen.subscribe(
() =>
alert('(Component2) onOpen');

);






following this plunker : http://plnkr.co/edit/SmntWy0GTNdvGB5Jb3hO?p=preview the method are called but, I would like to pass a parameter. how do I do this ?







angular observable






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 6:23









BobbyBobby

12610




12610







  • 1





    May be you can pass parameter in stream : callComponentMethod(params) this.onOpen.next(params);

    – junk
    Nov 14 '18 at 6:27











  • angularfirebase.com/lessons/…

    – Hoax
    Nov 14 '18 at 6:29











  • Which param you want to pass?

    – User3250
    Nov 14 '18 at 6:34











  • depends of where, right now I wish a custom typed object

    – Bobby
    Nov 14 '18 at 6:46












  • 1





    May be you can pass parameter in stream : callComponentMethod(params) this.onOpen.next(params);

    – junk
    Nov 14 '18 at 6:27











  • angularfirebase.com/lessons/…

    – Hoax
    Nov 14 '18 at 6:29











  • Which param you want to pass?

    – User3250
    Nov 14 '18 at 6:34











  • depends of where, right now I wish a custom typed object

    – Bobby
    Nov 14 '18 at 6:46







1




1





May be you can pass parameter in stream : callComponentMethod(params) this.onOpen.next(params);

– junk
Nov 14 '18 at 6:27





May be you can pass parameter in stream : callComponentMethod(params) this.onOpen.next(params);

– junk
Nov 14 '18 at 6:27













angularfirebase.com/lessons/…

– Hoax
Nov 14 '18 at 6:29





angularfirebase.com/lessons/…

– Hoax
Nov 14 '18 at 6:29













Which param you want to pass?

– User3250
Nov 14 '18 at 6:34





Which param you want to pass?

– User3250
Nov 14 '18 at 6:34













depends of where, right now I wish a custom typed object

– Bobby
Nov 14 '18 at 6:46





depends of where, right now I wish a custom typed object

– Bobby
Nov 14 '18 at 6:46












2 Answers
2






active

oldest

votes


















1














You have quite a few things incorrect with your implementation. Here is a working example of what you want to achieve:



Example



You don't need to use Subject, you can just use a normal observable and then "push" new values to the emitter for that observable:



export class CommunicationService {
// Observable string sources
private emitter: any;
public messageInbox: Observable<any>

constructor()
this.messageInbox = Observable.create(e => this.emitter = e);


// Service message commands
public SendMessage()
this.emitter.next("hello");



The code in your components was mostly ok.






share|improve this answer

























  • stackblitz.com/edit/angular-u36nnh thanks

    – Bobby
    Nov 14 '18 at 7:15












  • Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

    – Bobby
    Nov 14 '18 at 7:25












  • @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

    – Zze
    Nov 14 '18 at 7:36



















1














Call callComponentMethod function of CommunicationService class rather than calling onOpen. Second, if you want to pass the information you can do it through passing the value to callComponentMethod function.



Below is the modified code



CommunicationService



import Injectable from '@angular/core';
import Subject from 'rxjs/Subject';

@Injectable()
export class CommunicationService

// Observable string sources
private onOpen = new Subject<any>();

// Observable string streams
onOpen = this.onOpen.asObservable();

// Service message commands
callComponentMethod(info:any)
this.onOpen.next(info); //<-- pass the value to subscribers





Component1



import Component from '@angular/core';
import CommunicationService from './communication.service.ts'

@Component(
selector: 'app-comp1',
template: `
<button type="button" (click)="callMethod()">Call method from Component1</button>
`
)
export class Component1

constructor( private communicationService: CommunicationService )

callMethod = function ()
let obj = name : "john" ; //<-- you can pass the value from callMethod
this.communicationService.callComponentMethod(obj); //<-- changed here








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%2f53294228%2fcall-a-compnent-from-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









    1














    You have quite a few things incorrect with your implementation. Here is a working example of what you want to achieve:



    Example



    You don't need to use Subject, you can just use a normal observable and then "push" new values to the emitter for that observable:



    export class CommunicationService {
    // Observable string sources
    private emitter: any;
    public messageInbox: Observable<any>

    constructor()
    this.messageInbox = Observable.create(e => this.emitter = e);


    // Service message commands
    public SendMessage()
    this.emitter.next("hello");



    The code in your components was mostly ok.






    share|improve this answer

























    • stackblitz.com/edit/angular-u36nnh thanks

      – Bobby
      Nov 14 '18 at 7:15












    • Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

      – Bobby
      Nov 14 '18 at 7:25












    • @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

      – Zze
      Nov 14 '18 at 7:36
















    1














    You have quite a few things incorrect with your implementation. Here is a working example of what you want to achieve:



    Example



    You don't need to use Subject, you can just use a normal observable and then "push" new values to the emitter for that observable:



    export class CommunicationService {
    // Observable string sources
    private emitter: any;
    public messageInbox: Observable<any>

    constructor()
    this.messageInbox = Observable.create(e => this.emitter = e);


    // Service message commands
    public SendMessage()
    this.emitter.next("hello");



    The code in your components was mostly ok.






    share|improve this answer

























    • stackblitz.com/edit/angular-u36nnh thanks

      – Bobby
      Nov 14 '18 at 7:15












    • Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

      – Bobby
      Nov 14 '18 at 7:25












    • @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

      – Zze
      Nov 14 '18 at 7:36














    1












    1








    1







    You have quite a few things incorrect with your implementation. Here is a working example of what you want to achieve:



    Example



    You don't need to use Subject, you can just use a normal observable and then "push" new values to the emitter for that observable:



    export class CommunicationService {
    // Observable string sources
    private emitter: any;
    public messageInbox: Observable<any>

    constructor()
    this.messageInbox = Observable.create(e => this.emitter = e);


    // Service message commands
    public SendMessage()
    this.emitter.next("hello");



    The code in your components was mostly ok.






    share|improve this answer















    You have quite a few things incorrect with your implementation. Here is a working example of what you want to achieve:



    Example



    You don't need to use Subject, you can just use a normal observable and then "push" new values to the emitter for that observable:



    export class CommunicationService {
    // Observable string sources
    private emitter: any;
    public messageInbox: Observable<any>

    constructor()
    this.messageInbox = Observable.create(e => this.emitter = e);


    // Service message commands
    public SendMessage()
    this.emitter.next("hello");



    The code in your components was mostly ok.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 14 '18 at 10:25

























    answered Nov 14 '18 at 6:54









    ZzeZze

    9,79063767




    9,79063767












    • stackblitz.com/edit/angular-u36nnh thanks

      – Bobby
      Nov 14 '18 at 7:15












    • Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

      – Bobby
      Nov 14 '18 at 7:25












    • @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

      – Zze
      Nov 14 '18 at 7:36


















    • stackblitz.com/edit/angular-u36nnh thanks

      – Bobby
      Nov 14 '18 at 7:15












    • Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

      – Bobby
      Nov 14 '18 at 7:25












    • @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

      – Zze
      Nov 14 '18 at 7:36

















    stackblitz.com/edit/angular-u36nnh thanks

    – Bobby
    Nov 14 '18 at 7:15






    stackblitz.com/edit/angular-u36nnh thanks

    – Bobby
    Nov 14 '18 at 7:15














    Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

    – Bobby
    Nov 14 '18 at 7:25






    Sorry again, I am using this has kind of event, but, wouldn't EventEmitter be better ? Component A and C are not related. Also, I do not see why I need emitter and message, couldn't this be done with only 1 element ?

    – Bobby
    Nov 14 '18 at 7:25














    @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

    – Zze
    Nov 14 '18 at 7:36






    @Bobby Technically yes it could be a single var, however I personally think that this is a better implementation because in this case, I made the emitter private and the messageInbox public. So nothing outside this service can emit events - so separation of concerns. I'm sure EventEmitter would also work fine.

    – Zze
    Nov 14 '18 at 7:36














    1














    Call callComponentMethod function of CommunicationService class rather than calling onOpen. Second, if you want to pass the information you can do it through passing the value to callComponentMethod function.



    Below is the modified code



    CommunicationService



    import Injectable from '@angular/core';
    import Subject from 'rxjs/Subject';

    @Injectable()
    export class CommunicationService

    // Observable string sources
    private onOpen = new Subject<any>();

    // Observable string streams
    onOpen = this.onOpen.asObservable();

    // Service message commands
    callComponentMethod(info:any)
    this.onOpen.next(info); //<-- pass the value to subscribers





    Component1



    import Component from '@angular/core';
    import CommunicationService from './communication.service.ts'

    @Component(
    selector: 'app-comp1',
    template: `
    <button type="button" (click)="callMethod()">Call method from Component1</button>
    `
    )
    export class Component1

    constructor( private communicationService: CommunicationService )

    callMethod = function ()
    let obj = name : "john" ; //<-- you can pass the value from callMethod
    this.communicationService.callComponentMethod(obj); //<-- changed here








    share|improve this answer





























      1














      Call callComponentMethod function of CommunicationService class rather than calling onOpen. Second, if you want to pass the information you can do it through passing the value to callComponentMethod function.



      Below is the modified code



      CommunicationService



      import Injectable from '@angular/core';
      import Subject from 'rxjs/Subject';

      @Injectable()
      export class CommunicationService

      // Observable string sources
      private onOpen = new Subject<any>();

      // Observable string streams
      onOpen = this.onOpen.asObservable();

      // Service message commands
      callComponentMethod(info:any)
      this.onOpen.next(info); //<-- pass the value to subscribers





      Component1



      import Component from '@angular/core';
      import CommunicationService from './communication.service.ts'

      @Component(
      selector: 'app-comp1',
      template: `
      <button type="button" (click)="callMethod()">Call method from Component1</button>
      `
      )
      export class Component1

      constructor( private communicationService: CommunicationService )

      callMethod = function ()
      let obj = name : "john" ; //<-- you can pass the value from callMethod
      this.communicationService.callComponentMethod(obj); //<-- changed here








      share|improve this answer



























        1












        1








        1







        Call callComponentMethod function of CommunicationService class rather than calling onOpen. Second, if you want to pass the information you can do it through passing the value to callComponentMethod function.



        Below is the modified code



        CommunicationService



        import Injectable from '@angular/core';
        import Subject from 'rxjs/Subject';

        @Injectable()
        export class CommunicationService

        // Observable string sources
        private onOpen = new Subject<any>();

        // Observable string streams
        onOpen = this.onOpen.asObservable();

        // Service message commands
        callComponentMethod(info:any)
        this.onOpen.next(info); //<-- pass the value to subscribers





        Component1



        import Component from '@angular/core';
        import CommunicationService from './communication.service.ts'

        @Component(
        selector: 'app-comp1',
        template: `
        <button type="button" (click)="callMethod()">Call method from Component1</button>
        `
        )
        export class Component1

        constructor( private communicationService: CommunicationService )

        callMethod = function ()
        let obj = name : "john" ; //<-- you can pass the value from callMethod
        this.communicationService.callComponentMethod(obj); //<-- changed here








        share|improve this answer















        Call callComponentMethod function of CommunicationService class rather than calling onOpen. Second, if you want to pass the information you can do it through passing the value to callComponentMethod function.



        Below is the modified code



        CommunicationService



        import Injectable from '@angular/core';
        import Subject from 'rxjs/Subject';

        @Injectable()
        export class CommunicationService

        // Observable string sources
        private onOpen = new Subject<any>();

        // Observable string streams
        onOpen = this.onOpen.asObservable();

        // Service message commands
        callComponentMethod(info:any)
        this.onOpen.next(info); //<-- pass the value to subscribers





        Component1



        import Component from '@angular/core';
        import CommunicationService from './communication.service.ts'

        @Component(
        selector: 'app-comp1',
        template: `
        <button type="button" (click)="callMethod()">Call method from Component1</button>
        `
        )
        export class Component1

        constructor( private communicationService: CommunicationService )

        callMethod = function ()
        let obj = name : "john" ; //<-- you can pass the value from callMethod
        this.communicationService.callComponentMethod(obj); //<-- changed here









        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 7:12

























        answered Nov 14 '18 at 7:06









        Sunil SinghSunil Singh

        6,2022626




        6,2022626



























            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%2f53294228%2fcall-a-compnent-from-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

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            政党

            天津地下鉄3号線