盡管查看了檔案,但我不清楚如何在 if 條件下使用 Observable 引發錯誤,如下所示:
openCountrySearchDialog() {
const addRef = this.dialog.open(DiscoverCountriesEntriyDialogComponent, {
width: '600px',
id: 'tid-known-countries-dialog-component',
autoFocus: true,
disableClose: true,
data: []
});
addRef.afterClosed().subscribe(countries => {
if (countries.length > 10) {
console.log("Oops, we got more than 10 countries");
}
this.countries = countries;
this.changeDetector.detectChanges();
});
}
我嘗試了以下方法:
addRef.afterClosed().subscribe(
(countries) => {
this.countries = countries;
this.changeDetector.detectChanges();
},
(error) => {
if (this.countries.length > 10) {
console.log('Oops, we got more than ten countries', error);
}
}
)
我相信我必須使用 apipe()但如果是這樣,我沒有正確實施它:
addRef
.afterClosed()
.pipe(error => {
if (this.countries.length > 10) {
return error;
}
})
.subscribe(countries => {
this.countries = countries;
this.changeDetector.detectChanges();
});
uj5u.com熱心網友回復:
這個的簡單版本將在您訂閱后您可以查看 res
if (this.countries.length>10) {
throw throwError(response);
}
通過錯誤從 rxjs 匯入,您將能夠捕獲您的錯誤
,
(error) => {
console.log(error)
}
}
uj5u.com熱心網友回復:
MatDialogRef afterClosed() 不會引發錯誤。因此,您可以做的是通過 close() 方法回傳包含錯誤邏輯的 ReturnObjects。
// open dialog:
const dialogRef = this.dialog.open(DialogExample);
dialogRef.afterClosed().subscribe((result: DialogData) => {
if (result.customResult === DialogResponse.ERROR) {
// do error handling here with 'result.customBody'
console.error('error response from afterClosed is: ', result.customBody);
} else {
// do success handling here with 'result.customBody'
console.log('succes response from afterClosed is: ', result.customBody);
}
});
匯出介面和列舉:
export interface DialogData {
customResult: DialogResponse;
customBody: any;
}
export enum DialogResponse {
SUCCESS = 'success',
ERROR = 'error',
}
對話框示例:
// dialog-example.ts
@Component({
selector: 'dialog-example',
templateUrl: 'dialog-example.html',
})
export class DialogExample {
constructor(
public dialogRef: MatDialogRef<DialogExample>,
@Inject(MAT_DIALOG_DATA) public data: DialogData
) {}
public closeWithSuccess() {
this.dialogRef.close(
{
customResult: DialogResponse.SUCCESS,
customBody: 'all happy ;-)'
}
);
}
public closeWithFail() {
this.dialogRef.close(
{
customResult: DialogResponse.ERROR,
customBody: 'more than 10 countries do not exist on this planet, lolz'
});
}
}
和對話框html:
// dialog-example.html:
<button (click)="closeWithSuccess()">close with success</button>
<button (click)="closeWithFail()">close with fail</button>
堆疊閃電戰
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/516432.html
標籤:有角度的可观察的
