我想将表单值传递给要在Observable中使用的服务。如何在组件中注入服务时传递名称值?该服务一直在使用环境变量,但我是通过表单自定义名称。谢谢!
class Component {
constructor(private myService: MYService){}
customer: Customer = new Customer();
updateService(customerForm: NgForm){ ..get it to service
customerForm.value.name; }
class MyService {
openId: Observable<OpenId>;
constructor(private http: Http, private router: Router){
\\ How do I get this.name from component?
this.openId = this.getOpenID(this.name);
}
private getOpenId(name: string): Observable<OpenId>{
return this.http.get(`${name}`).map(res => res.json()).publishlast().refCount();
}
答案 0 :(得分:0)
在您的组件中。请注意您如何订阅服务公开的Observable
class Component {
customer: Customer = new Customer();
constructor(private service: Service){}
updateService(customerForm: NgForm){
this.service.updateService(customerForm.value.name)
.subscribe(response => response);
}
}
在您的组件中自定义您的名称后,您将其传递到服务中的公共方法updateService,之后将其传递到您的服务中
class Service {
openId: Observable<OpenId>;
updateService(name: string): Observable<any> {
return this.http.get(`${name}`).map(res =>
res.json()).publishlast().refCount();
}
}
答案 1 :(得分:0)
如果您已经在组件的构造函数中启动了服务,那么您不能在以后的组件中将值传递给服务的构造函数。我认为您需要做的是在组件中创建局部变量或FormGroup,然后通过表单提交等事件将其发送到服务。
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
@Component( {
templateUrl: 'mycomponent.html',
} )
export class MyComponent {
customerForm : FromGroup;
constructor(private myService: MyService){}
ngOnInit() {
this.customerForm = this.formBuilder.group( {
name : ""
} );
}
// Call this on your form submit, and optionally subscribe to the observable
updateService() {
this.myService.getOpenId( this.customerForm.get( "name" ).value ).subscribe( {
data => {},
error => {}
} );
}
}
export class MyService {
constructor(private http: Http){}
// Make this method publicly accessible, or modify it to suit your need
getOpenId(name) : Observable<OpenId> {
return this.http.get(`${name}`).map(res => res.json()).publishlast().refCount();
}
}
当然,您需要在模板中使用您的表单。这样的事情会做:
<form [formGroup]="customerForm" (ngSubmit)="updateService()">
<input type="text" name="name" formControlName="name" />
<input type="submit" value="Submit">
</form>
由于其灵活性,我使用ReactiveForm构建了此示例。如果您这样做,请确保将其导入app.module。
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule,
FormsModule
],
......
})
export class AppModule { }