Angular:来自具有服务共享功能的不同组件的调用函数 [英] Angular : Call Function from different component with Service Sharing

查看:53
本文介绍了Angular:来自具有服务共享功能的不同组件的调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现这一目标-

// 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 ?

推荐答案

您可以基于可观察对象使用以下服务.它使用消息作为字符串,但是如果需要在组件之间传递数据,则可以使其更通用.在我的常规服务中,我通常会传递一条包含例如消息类型和消息数据的消息

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆