首页 > 解决方案 > Angular 8 返回 Observable从函数

问题描述

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

标签: angular

解决方案


您可以从 '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>; 

推荐阅读