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() { }
}
非常感謝您爲每一個建議潛在的解決方案。
我真的很感激!
謝謝您的回答。但我不明白如何處理form.component.ts中的最後一行。我從'this.AddwmslayerService.setLayer()'中得到一個錯誤。我在app.module中提供了該服務。 – Steffn
您是否在form.component.ts的構造函數中添加了依賴項'private addLayerService:AddwmslayerService'? –
非常感謝,現在它的工作;)出於興趣:你知道如何直接在組件中注入兩個值而不需要服務?這也是一個不錯的解決方案。 – Steffn