反应形式:使用角度4注入服务中的形式值

时间:2017-08-02 09:28:16

标签: angular angular-reactive-forms

我想在服务中使用两个表单值。
但我没有获得方法/语法来注入服务中的值,以便在其他组件中提供它们。
这是我的表单的代码:

form.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-formurl',
  templateUrl: './formurl.component.html',
  styleUrls: ['./formurl.component.css']
})
export class FormurlComponent  {

  rForm: FormGroup;
  post: any;            // property: weitergeben an Service
  url: string = '';
  name: string = '';


  constructor(private fb: FormBuilder) {

    this.rForm = fb.group({
      'name': [''],
      'url': ['']
    });

  }


  addPost(post) {

    this.name = post.name;
    this.url = post.url;

    }

}

form.component.html

 <form [formGroup]='rForm'  (ngSubmit)="addPost(rForm.value)">

    <label>
    <input type="text" formControlName="name">
    </label>

    <label>
      <input type="text" formControlName="url">
    </label>

    <input type="submit" class="button expanded" value="Submit Form">

</form>


我想注入价值观&#39; name&#39;和&#39; url&#39;在这项服务中:

service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AddwmslayerService {


  addlayer = {

    addlayername: ??????????????? ,
    addlayerurl: ??????????????????,

  };

  constructor() { }

}

非常感谢您提出的每一个可能的解决方案 我真的很感激!

1 个答案:

答案 0 :(得分:0)

您可以在服务中创建set方法,然后在提交表单后调用它。但是您必须在app.module.ts中提供服务。

<强> service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AddwmslayerService {


  addlayer = {

    addlayername: '',
    addlayerurl: '',

  };

  constructor() { }

  setLayer(name: string, url: string) {
    this.addlayer.addlayername = name;
    this.addlayer.addlayerurl = url;
  }

}

<强> form.component.ts

...
constructor(private fb: FormBuilder, private addLayerService: AddwmslayerService) {

    this.rForm = fb.group({
        'name': [''],
        'url': ['']
    });

}


addPost(post) {

    this.name = post.name;
    this.url = post.url;

    this.addLayerService.setLayer(this.name, this.url);
}
...