在Angular项目之外,还有一个TS类,我正试图通过该类通过服务将对象发送到angular组件。
this.internalChart.series[0].data.forEach(data => { // FIND A POINT IN ALL MAP
if (data.name === SelectedName1) { // IF A POINT IS FOUND...
data.doDrilldown() // DRILLDOWN TO CHILD MAP
// HERE I MUST WAIT. WHEN DODRILLDOWN ENDS, CONTINUE WITH BELOW CODE
// UNDERSTANDING "ENDS" WHEN NEW MAP AND ITS DATA IS LOADED AND READY
this.internalChart.options.drilldown.series[0].data.forEach(dataInside => { // FOR EACH POINT OF NEW MAP (DRILLDOWN/CHILD MAP)
if (dataInside.name === SelectedName2) { // IF A POINT IS FOUND
this.setState({ province: dataInside['hc-key'] }); // CHANGE STATE
}
});
}
});
是TS类,它使用Angular服务发送对象;
sender.ts
export class Sender {
injector;
servicePointer;
myData: Object;
constructor() {
this.injector = Injector.create({
providers: [
{
provide: ShareDataService,
deps: []
},
]
});
this.servicePointer = this.injector.get(ShareDataService);
}
public send() {
this.myData = {
name: "Robert",
visible: true
}
return this.servicePointer.dataVisibility(this.myData);
}
}
是一个Angular服务,已成功从share-data.service.ts
类接收对象:
sender.ts
@Injectable({
providedIn: 'root'
})
export class ShareDataService {
changeDataSource = new BehaviorSubject<Object>({});
public dataUpdate$ = this.changeDataSource.asObservable();
public dataVisibility = (dataInfo: Object) => {
//console.log(dataInfo);
this.changeDataSource.next(dataInfo);
}
}
包括app.component.ts
TS类,并调用Sender
方法:
.send()
至少有一个export class AppComponent implements OnInit {
private foo:Sender.Sender = new Sender.Sender();
constructor() {}
ngOnInit() {
this.foo.send();
}
}
组件可以订阅服务:
receive
并始终从服务返回空对象,尽管带有数据的对象进入服务(console.log(dataInfo))。
是什么原因引起的? export class ReceiverComponent implements OnInit {
constructor(private shareDataService: ShareDataService) { }
receivedData;
ngOnInit() {
this.shareDataService.dataUpdate$.subscribe(success => {
this.receivedData = success;
console.log(this.receivedData);
})
}
}
中有
service
具有根应用程序注入器的 decorator,在@Injectable({
providedIn: 'root'
})
类中,还提供了一个服务注入器。可能是这个问题吗?如果是这样,还有其他方法可以注入服务吗?
还有一个stackblitz,上面有解释的代码。