加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 从另一个组件调用组件中的函数

发布时间:2020-12-17 07:36:13 所属栏目:安全 来源:网络整理
导读:在Angular2中,假设我有component1(使用它作为左面板导航器)和component2.这两个组件彼此不相关(兄弟,父和子,……). 如何从component2调用component1中的函数? 我不能在这里使用事件绑定. 共享服务是非相关组件之间通信的常用方式. 您的组件需要 use a singl
在Angular2中,假设我有component1(使用它作为左面板导航器)和component2.这两个组件彼此不相关(兄弟,父和子,……).
如何从component2调用component1中的函数?
我不能在这里使用事件绑定.
共享服务是非相关组件之间通信的常用方式.
您的组件需要 use a single instance of the service,因此请确保它在根级别提供.

共享服务:

@Injectable()
export class SharedService {

    componentOneFn: Function;

    constructor() { }
}

第一部分:

export class ComponentOne {

    name: string = 'Component one';

    constructor(private sharedService: SharedService) {
        this.sharedService.componentOneFn = this.sayHello;
    }

    sayHello(callerName: string): void {
        console.log(`Hello from ${this.name}. ${callerName} just called me!`);
    }
}

第二部分:

export class ComponentTwo {

    name: string = 'Component two';

    constructor(private sharedService: SharedService) {
        if(this.sharedService.componentOneFn) {
            this.sharedService.componentOneFn(this.name); 
            // => Hello from Component one. Component two just called me!
        }
    }
}

这篇文章也许有帮助:Angular 2 Interaction between components using a service

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读