角度 8 返回<boolean> 可从函数中观察



如何在函数GetDataFromService()中返回Observable<boolean>afterthis.Form = new FormGroup(formControls);

目录

<form *ngIf="loading | async" [formGroup]="Form" class="example-form">
</form>
<mat-spinner *ngIf="!loading | async"></mat-spinner>

TS

import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormGroup, FormBuilder, AbstractControl, FormControl } from '@angular/forms';
import { Observable, observable } from 'rxjs';
@Component({
selector: 'app-add-product-dialog',
templateUrl: './add-product-dialog.component.html',
styleUrls: ['./add-product-dialog.component.css']
})
export class AddProductDialogComponent implements OnInit {
properties: any;
Form: FormGroup = new FormGroup({});
loading: Observable<boolean>;
constructor(private formBuilder: FormBuilder,
public dialogRef: MatDialogRef<AddProductDialogComponent>,
private http: HttpClient) {
this.loading = this.GetDataFromService();
}
GetDataFromService(): Observable<Boolean> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
let formControls: { [key: string]: AbstractControl } = {};
this.http.get("https://localhost:44346/api/Values/GetDrillsProperties", { headers: headers }).subscribe(data => {
this.properties = data
Object.keys(this.properties).forEach(element => {
formControls[element] = new FormControl();
});
this.Form = new FormGroup(formControls);
});
}
}

你可以从'rxjs/operator'导入map并使用它

return this.http.get("https://localhost:44346/api/Values/GetDrillsProperties", { headers: headers }).pipe(map(res => {
this.properties = res
Object.keys(this.properties).forEach(element => {
formControls[element] = new FormControl();
})
this.Form = new FormGroup(formControls);
return true;
})) as Observable<boolean>; 

您可以通过添加 return 关键字来做到这一点 你得到调用并在this.form喜欢之后返回布尔值

return this.http.get("https://localhost:44346/api/Values/GetDrillsProperties", { headers: headers }).subscribe(data => {
this.properties = data
Object.keys(this.properties).forEach(element => {
formControls[element] = new FormControl();
});
this.Form = new FormGroup(formControls);
return true;
}); 

但是,与其使加载异步,为什么不将其更改为布尔值,例如

loading:boolean=true;
this.GetDataFromService().subscribe(d=>{
//here set loading to false
})

在 html 上使用像

<mat-spinner *ngIf="loading"></mat-spinner>

最新更新