简体   繁体   English

没有 HTML 的两个组件之间的角度共享

[英]Angular Sharing between two components without HTML

I HAVE, 1.topbar folder - contains html(1) and ts(1) for topbar 2.page folder - contains html(2) and ts(2) for page我有,1.topbar 文件夹 - 包含 html(1) 和 ts(1) 用于 topbar 2.page 文件夹 - 包含 html(2) 和 ts(2) 用于页面

Now i have a BUTTON in html(1)现在我在 html(1) 中有一个按钮

<button (click)="refresh()" class="navbar-btn btn btn-success btn-md refresh">
    <span class="glyphicon glyphicon-refresh"></span> Refresh
</button>

Now i have a function in ts(1)现在我在 ts(1) 中有一个函数

refresh()
{
console.log("this is topbar html and ts");
}

NOW i have a function in html(2)现在我在 html(2) 中有一个函数

Here ,i dont want to do anything!在这里,我什么都不想做!

NOW,i have a function in ts(2)现在,我在 ts(2) 中有一个函数

refreshEvent(){
console.log("i want use this function in html(1) BUT HOW??")
}

So,As I click button it should call refreshEvent()所以,当我点击按钮时,它应该调用 refreshEvent()

You can use Subject from rxjs,您可以使用 rxjs 中的主题,

import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MyService {
    private subject = new Subject<any>();
    refresh() {
        this.subject.next();
    }
    onRefresh(): Observable<any> {
        return this.subject.asObservable();
    }
}

Component B:组分 B:

  constractor(private myService: MyService){}
  this.$subscription = this.myService.onRefresh().subscribe(() => this.refreshEvent() );
  ngOnDestroy() {
        this.$subscription .unsubscribe();
    }

Component A:组件 A:

constractor(private myService: MyService){}

refresh()
{
  //console.log("this is topbar html and ts");
 this.myService.refresh();
}

If they have a child-parent relationship you can use output event, see the documentation for more info: https://angular.io/guide/component-interaction如果他们有父子关系,您可以使用输出事件,请参阅文档以获取更多信息: https : //angular.io/guide/component-interaction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM