我需要你的帮助!我需要从“结果”中获取一个值到我的外部服务。但是它有一些麻烦,可能是因为异步工作。如何从我的组件中获取它?我的 Angular 版本是 12。这是我的代码:
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ModalComponent } from '../modal/modal.component';
@Injectable({
providedIn: 'root'
})
export class ModalResultService {
param!:string
constructor(
public dialog: MatDialog
) { }
dialogResult(){
let dialogRef = this.dialog.open(ModalComponent)
dialogRef.afterClosed().subscribe(
result => {
console.log(result);
}
)
}
}
在我的外部服务中,我想做这样的事情
update(note: Notation): Observable<Notation> {
if (this.res.dialogResult())
return this.http.patch<Notation(`${environment.fbDbUrl}/posts/${note.id}.json`, note);
return of(this.dNotation)
}
dNotation 是一些默认对象
您需要一直返回一个Observable
并使用异步代码。
dialogResult(): Observable<Boolean> {
let dialogRef = this.dialog.open(ModalComponent)
return dialogRef.afterClosed();
}
在您的其他服务中:
update(note: Notation): Observable<Notation> {
this.res.dialogResult().pipe(
mergeMap(result => {
if(result) {
return this.http.patch<Notation(`${environment.fbDbUrl}/posts/${note.id}.json`, note);
} else {
return of(this.dNotation);
}
}
);
}
注意:阅读 RxJs 文档mergeMap
以查看它是否适合您的用例。也许另一个运营商更合适。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句