Angular 6数据绑定到服务

时间:2018-07-30 19:33:26

标签: angular mean-stack

我的MEAN Stack应用程序需要显示MongoDB数据库中的表单数据,并允许用户更新信息。我的后端Node / Express API可用于所有CRUD操作,但是我有 troule在事物的角度方面实现更新功能。首先,我向API发出一个http请求,该请求返回指定形式的所有数据,并将{{form.property}}放入 各个HTML输入字段的value属性。为了跟踪更改,我使用ngModel(在HTML中),自定义Angular服务和一系列设置器-每个字段一个(请参见下文)。

但是,由于设置器是在模板渲染之前定义的,因此通过http获得的值不会分配给ngModel,因此不会提交给API。结果,只有 提交已更改的字段。 如何确保在提交之前将通过http get请求获得的值实际分配给服务?

HTML

<input[(ngModel)]="field" type="text" value="{{ forms?.field}}">

组件(ts)

constructor(public _updateformService: UpdateformService, 
public http: HttpClient){
    this.http.get(this.API_URL).subscribe(result => {
      this.forms = result as Form[];
    }, error => console.error(error));
    }
...

set field(value: string) {
  this._updateformService.field = value;
}

...

updateForm() {
    var formdata = {
        field: this._updateformService.field
    }
    this.http.put(this.queryURL, formdata).subscribe(
      res => {
        console.log(res);
        alert("Document submitted.");
      },
      err => {
        console.log('Error occured');
        alert("Error. Did not submit.");
      }
    );
  }

服务(ts)

export class UpdateformService {
  field: string = '';

1 个答案:

答案 0 :(得分:0)

通常最好的做法是让服务实现服务器调用的逻辑。该组件仅用于演示。以下代码只是一种指导。也许您需要调整某些零件以使其适合您的需求。

HTML

<input[(ngModel)]="field" type="text" value="{{forms?.field}}"/>

组件(ts)

import {Subscription} from 'rxjs';

private forms: Array<Form> = [];
private field: string = '';
private subscriptions: Subscription;


constructor(
    private _updateformService: UpdateformService
){ }

ngOnInit(): void {
    this.subscriptions.add(
        // as soon as field in the service gets a new value this.field gets updates
        this._updateformService.getField.subscribe(_field => {
            this.field = _field;
        })      
    );

    this.subscriptions.add(   
        // as soon as forms in the service gets a new value this.forms gets updates     
        this._updateformService.getForms.subscribe(_forms => {
            this.forms = _forms;
        })      
    );
} 

ngOnDestroy(): void {
    // unsubscribe from all subscriptions when destroying the component
    this.subscriptions.unsubscribe();
}

updateForm() {
    this._updateformService. updateForm(this.field);
}

服务(ts)

import {Observable, BehaviorSubject} from 'rxjs';

export class UpdateformService {
  private forms: BehaviorSubject<Array<Form>> = new BehaviorSubject<>([]);
  private field: BehaviorSubject<string> = new BehaviorSubject<>(string);

  constructor(public _updateformService: UpdateformService, 
      public http: HttpClient){
          this.http.get(this.API_URL).subscribe(result => {
          // update the value of forms
          this.forms.next(result as Array<Form>);
      }, error => console.error(error));
  }

  public updateForm(formdata: any): void {
      this.http.put(this.queryURL, formdata).subscribe(
      res => {
        console.log(res);
        alert("Document submitted.");
      },
      err => {
        console.log('Error occured');
        alert("Error. Did not submit.");
      }
    );
  }

  public setField(value: string) {
      // update the value of field
      this.field.next(value);
  }

  public getField(): Observable<string> {
      return this.field.asObservable();
  }

  public getForms(): Observable<Array<Form>> {
      return this.forms.asObservable();
  }
}