我使用的是Angular 11,我在componentB中有很多方法(单向调用)
我现在必须从componentA中调用许多存在于componentB中的方法。
我知道我可以将所有的方法移动到一个服务中,但是在这种情况下,这将是大量的工作,我只需要一个快速的解决方案。
所以我想保持componentB是什么样子,并能够从componentA调用它的方法。
componentA和componentB不相关。
是否有一个解决方案来做到这一点,而不必把方法从组件b ?
你可以通过service来实现,它将被注入到两个组件中服务可以像这样
@Injectable()
class MyDataService implements IMyDataService {
private whenMessageRecieved$: Subject<MyDataType> =
new ReplaySubject(1);
constructor(
) {
}
public notify(someData: MyDataType): void {
this.whenMessageRecieved$.next(someData);
}
public whenMessageRecieved(): Observable<MyDataType> {
return this.whenMessageRecieved$.asObservable();
}
}
ComponentB应该订阅whenmessagerreceived (), componentA应该使用严格的参数调用notify。在不久的将来,该服务将帮助您从componentB中迁移方法
但仍然-最好将公共逻辑存储在其他地方,而不是在componentB