Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

angular - call a function in a component from another component

In Angular2 , assume I have component1(use it as left panel navigator) and component2 .these two components are not related to each other (sibling, parent and child, ...). how can I call a function in component1 from component2? I cant use event binding here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use angular BehaviorSubject for communicating with non related component.

Service file

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class commonService {
    private data = new BehaviorSubject('');
    currentData = this.data.asObservable()

    constructor() { }

    updateMessage(item: any) {
        this.data.next(item);
    }

}

First Component

constructor(private _data: commonService) { }
shareData() {
      this._data.updateMessage('pass this data');
 }

Second component

constructor(private _data: commonService) { }
ngOnInit() {
     this._data.currentData.subscribe(currentData => this.invokeMyMethode())
}

Using above approach you can invoke a method/share data easily with non related components.

More info here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...