繁体   English   中英

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

[英]Angular Sharing between two components without HTML

我有,1.topbar 文件夹 - 包含 html(1) 和 ts(1) 用于 topbar 2.page 文件夹 - 包含 html(2) 和 ts(2) 用于页面

现在我在 html(1) 中有一个按钮

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

现在我在 ts(1) 中有一个函数

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

现在我在 html(2) 中有一个函数

在这里,我什么都不想做!

现在,我在 ts(2) 中有一个函数

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

所以,当我点击按钮时,它应该调用 refreshEvent()

您可以使用 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();
    }
}

组分 B:

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

组件 A:

constractor(private myService: MyService){}

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

如果他们有父子关系,您可以使用输出事件,请参阅文档以获取更多信息: https : //angular.io/guide/component-interaction

暂无
暂无

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

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