2017-08-02 91 views
0

我想在服务中使用两个表单值。
但我没有得到方法/语法来注入服务中的值,以便在其他组件中注入它们。
这里是我的形式代码:反应形式:在角度服务中注入表单值4

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> 


,我想注入此服务中的值“名称”和“网址”:

service.ts

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

@Injectable() 
export class AddwmslayerService { 


    addlayer = { 

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

    }; 

    constructor() { } 

} 

非常感谢您为每一个建议潜在的解决方案。
我真的很感激!

回答

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); 
} 
... 
+0

谢谢您的回答。但我不明白如何处理form.component.ts中的最后一行。我从'this.AddwmslayerService.setLayer()'中得到一个错误。我在app.module中提供了该服务。 – Steffn

+0

您是否在form.component.ts的构造函数中添加了依赖项'private addLayerService:AddwmslayerService'? –

+0

非常感谢,现在它的工作;)出于兴趣:你知道如何直接在组件中注入两个值而不需要服务?这也是一个不错的解决方案。 – Steffn