Angular 8从函数返回Observable <boolean>

时间:2019-10-12 14:08:38

标签: angular

如何在函数Observable<boolean>中返回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);
    });
  }
}

2 个答案:

答案 0 :(得分:1)

您可以通过在您的通话中添加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>

答案 1 :(得分:1)

您可以从“ 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>; 
相关问题