[英]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.