0

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

html

<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);
    });
  }
}
4

2 回答 2

2

您可以从 'rxjs/operators' 导入地图并使用它

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>; 
于 2019-10-12T17:05:39.103 回答
1

您可以通过添加一个 return 关键字来获得调用并在this.formlike之后返回布尔值

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>
于 2019-10-12T14:20:18.697 回答