我尝试了许多可能的解决方案,这些解决方案几乎与在共享服务中使用 ReactiveX Observables 的解决方案完全相同。我可以在服务中触发 change() 函数,但据我所知……总是这样。this.dataSource.next(param) 不会触发 component2 中的 Observable data$。我尝试的一个示例解决方案是在 Angular 5 中手动广播事件。请帮忙。
.
.
Import { EventProxyService } from ‘event-proxy.service’
@Component({
.
.
providers: [ EventProxyService ]
})
export class Component1 {
constructor(private eventProxyService: EventProxyService){}
onClick(){
console.log(“onClick clicked”)
this.eventProxyService.change(“1”)
}
}
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs/Observable'
import { Subject } from 'rxjs/Subject'
@Injectable()
export class EventProxyService {
private dataSource = new Subject<any>()
data$ = this.dataSource.asObservable()
change(param: any) {
console.log("in service", param)
this.dataSource.next(param)
}
}
Import { EventProxyService } from ‘event-proxy.service’
@Component({
.
.
providers: [ EventProxyService ]
})
export class Component2 implements OnInit {
constructor(private eventProxyService: EventProxyService){}
ngOnInit() {
this.eventProxyService.data$.subscribe((param: any) => {
console.log("in jobs", param)
})
}
}