What I'm Trying To Do
在我的Angular客户端应用程序中有两个不相关的组件,第一个组件负责从服务器获取和处理数据.我try 使用subscribe回调函数导航到一个新页面并显示处理过的数据(blob).更具体地说,我想转到一个新的标签页,并使用一个无关的组件预览word文档.我发现可以使用带有RxJS主题的服务通过不相关的组件传递数据.
What I'm Getting
我已经实现了一些代码,但是blob没有到达预览组件.
What I've tried
这是我想出的一些代码:
Service for transferring a Blob object
@Injectable()
export class DocPreviewService {
private blob = new BehaviorSubject<Blob | undefined>(undefined);
public share$ = this.blob.asObservable();
constructor() {}
setBlob(blob: Blob) {
this.blob.next(blob);
}
}
Function responsible for retrieving the blob from the server (first component)
showReport(selected_id: string) {
const url = this.router.serializeUrl(this.router.createUrlTree([`tools/${selected_id}/preview`]));
// it's important that the page opens in a new tab
window.open(url, '_blank');
this.report_service.createReport(this.calc_items[selected_id]).subscribe({
next: (doc_blob: Blob) => {
{
this.doc_preview_service.setBlob(doc_blob);
}
},
error: (error: any) => {
},
})
}
Component responsible for viewing a document (second component)
export class DocPreviewComponent implements OnChanges, AfterViewInit, OnDestroy {
doc_blob?: Blob;
@ViewChild('doc_preview') doc_preview!: ElementRef;
subscription: Subscription;
constructor(private doc_preview_service: DocPreviewService, private local_storage: LocalStorageService) {
this.subscription = this.doc_preview_service.share$.subscribe(blob => {
this.doc_blob = blob;
});
}
ngOnChanges(changes: SimpleChanges): void {}
ngAfterViewInit(): void {
if (this.doc_blob) {
doc.renderAsync(this.doc_blob, this.doc_preview.nativeElement)
.then(x => console.log("docx: finished"));
}
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
任何帮助将不胜感激.谢谢