从另一个不使用 EventEmitter() 的组件调用函数

Call function from another component not working with EventEmitter()

我需要从组件A调用函数到vomponent B。 我为获取用户提供服务 service.ts

getUsers(): Observable<UserModel[]> {
return this.httpClient.get<UserModel[]>(environment.BASE_URL + this.apiurlAllUsers + "all").pipe(
  catchError(this.handleError)
);

}

然后在 component A 中,我调用此服务并为 ng-bootstrap table

设置数据
 getUsersInList() {
this.userService.getUsers().subscribe((data: UserModel[]) => {
  this.collectionSize = data.length;
  this.allUsers = data;
});
}

现在当我在 component B(我的模态框)中提交数据时,从 component A

调用函数 getUsersInList()

我尝试使用@Output

component B
@Output trigger: new EventEmitter();

submitForm(){
   this.trigger.emit("hello from B");
}


 component A
 parentFn($event: string) {
console.log($event);
this.getUsersInList();
}

什么也没发生...

还有,我试试

@Input second: componentA
and directly call function

this.second.getUserInList() //but I get errors

谢谢

好吧,我看不到你的 html,但是如果 componentA 是 componentB 的父级,那么应该是这样的:

 <app-component-b (trigger)=functionThatIsInParent($event)> 

这就是您将输出传递给父级的方式。

编辑观察结果:
在服务中创建一个主题:

public whatever = new Subject<any>();

然后你必须创建这个:

getThatObservable(): Observable<any> {
    return.this.whatever.asObservable();
}

还有这个:

updateObservable(data) {
   this.whatever.next(data);
}

然后提交:

submitForm(){ this.service.updateObservable("hello from B"); }

然后在componentA:

this.service.getThatObservable().subscribe( data => {
         // do whatever with data
      });

当然这只是其中一种解决方案您也可以不创建 updateObservable 并直接调用:

this.service.whatever.next("hello from B");