对于我的应用程序,我必须与 2 个组件通信,但这些组件没有父子关系。
我使用一项服务来设置此通讯。当我单击 component1 上的按钮时,我会在 compenent2 中触发一个函数。通常,当我从 component2 触发它时,此函数会更改 component2 的 html。但是当我从 component1 触发它时,什么也没有发生。当component1触发component2中的函数时,有没有办法重新加载/更新HTML?
多谢!
对于我的应用程序,我必须与 2 个组件通信,但这些组件没有父子关系。
我使用一项服务来设置此通讯。当我单击 component1 上的按钮时,我会在 compenent2 中触发一个函数。通常,当我从 component2 触发它时,此函数会更改 component2 的 html。但是当我从 component1 触发它时,什么也没有发生。当component1触发component2中的函数时,有没有办法重新加载/更新HTML?
多谢!
就我使用它而言,您的服务通信一定有问题,对我来说效果很好。确保您订阅了要在其中接收任何值的组件的构造函数中的服务。在你的情况下,
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
}
);
我希望它会帮助你!