Angular:从具有服务共享的不同组件调用函数 [英] Angular : Call Function from different component with Service Sharing
问题描述
我想实现这个 -
// component1
load(){
// code...
}
// component2
component1.load();
所以,基本上我只想从一个组件调用不同组件的函数.
So, basically I just want to call function of different component from a component.
我在互联网上读到有 3 种方法可以在组件之间共享数据,在我的应用程序中,我使用服务共享在我的组件之间共享数据.
I have read through the internet that there are 3 ways to share data between components, In my app, I am using Service Sharing to share data between my components.
但是如何通过服务共享方法简单地从不同组件调用函数?
But how I can simply call a function from different component with service sharing approach ?
推荐答案
您可以使用以下基于 observables 的服务.它使用消息作为字符串,但如果您需要在组件之间传递数据,您可以使其更通用.在我的正常服务中,我通常会传递一个包含消息类型和消息数据的消息,例如
You can use the following service based on observables. It's using messages as string, but you can make it more generic if you need to pass data between components. In my normal services, I usually pass a message that contains message type and message data for instance
基本上,一个组件组件广播一条消息,另一个组件监听消息
Basically, one component compoennt broadcast a message, and the other one listen to messages
试试这个
message-service.ts
import {Injectable} from '@angular/core';
import {Observable, Subject} from "rxjs";
@Injectable()
export class MessageService
{
//subject to trigger events
private mySubject: Subject<any> = new Subject<string>();
//observable to listen to events
public readonly messageReceived$: Observable<string> = this.mySubject.asObservable();
//
brodcast(message: string)
{
this.mySubject.next(message );
}
}
component1.ts
constructor(private service: MessageService){}
//...
this.service.broadcast('triggerLoadMethod'); //broadcast a message for service subscriber to receive
component2
constructor(private service: MessageService)
{
//subscribe to observableto receive messages
this.service.messageReceived$.subscribe( message =>
{
if(message == 'triggerLoadMethod') //if we are interested in the message, process it
{
this.load();
}
});
}
这篇关于Angular:从具有服务共享的不同组件调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!