Angular5 manipulation Html of other component without having child/parent relation

吃可爱长大的小学妹 提交于 2020-01-06 06:04:42

问题


For my application I have to communicate with 2 components but these components don`t have a parent child relation.

I use a service to set up this comminication. When I click on the button on of component1 I trigger a function in compenent2. Normaly this function makes a change in the html of component2 when i trigger it from component2. But when I trigger it from component1 nothing happens. Is there a way to reload/update the HTML when component1 triggers the function in component2?

THx a lot!


回答1:


There must be issue with your service communication, as far as I have used it, worked fine for me. Make sure you subscribe to the service in constructor of component in which you want to receive any value. In your case,

 import { Subject,Observable, of } from 'rxjs';
 code for service :
   public methodForRender = new Subject<any>();
   renderMe = this.methodForRender.asObservable();
   callMethodToRender(value) {
    this.methodForRender.next(value);
   }

 code for component 1 :  which is triggering function!

   constructor(private callingBridge: SharedService) {}
   this.callingBridge.callMethodToRender(this.value);

 code for component 2 :  which should be subscribed to service 

    constructor(private callingBridge: SharedService) {}
    this.callingBridge.renderMe.subscribe(
     (value) => {
        // do your stuff // call your function here to render html
       }
    );    

I hope it will help you!



来源:https://stackoverflow.com/questions/50755984/angular5-manipulation-html-of-other-component-without-having-child-parent-relati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!