使用输入形式Angular更新服务变量?

时间:2018-05-19 21:56:07

标签: angular typescript angular5

我想更新Angular中服务内部的变量。 我想点击按钮时用输入表单更新变量。

这是服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class DashService {
  input: number = 0; //Varible that need update
  constructor(private http: HttpClient) { }
  public getVar() {
    return this.input;
  }
  public insertData(data) {
    this.input = data
  }
}

这是组件

import { DashService } from './dash.service';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private service: DashService) { }

  ngOnInit() {
    console.log(  this.service.getVar())
  }
}

这是组件Html

    <form (submit)="onSubmit(input)">
   <div class="form-group">
    <label>Age</label>
      <input type="numer" class="form-control" [(ngModel)]="age" age="age">
   </div>
   <input type="submit" class="btn btn-success" value="Submit">
</form>

2 个答案:

答案 0 :(得分:0)

由于您的代码中的信息较少,我不太了解您的问题,因此请尝试使用此链接,我认为这是使用跨组件通信通过EventEmitter传输数据的最佳方式:

https://angular.io/guide/component-interaction

或者您可以使用来自rxjs的Subject作为观察者和Observable:

http://reactivex.io/documentation/subject.html

答案 1 :(得分:0)

这应该有用。

服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';



@Injectable()
export class DashService {
  input = new BehaviorSubject('test');; //Varible that need update
  constructor(private http: HttpClient) { }

  public getVar() {
    return this.input.asObservable();
  }
  public insertData(data) {
    this.input.next(data);
  }
}

成分<​​/ P>

export class AppComponent {
    public age = '';
    constructor(public service: DashService) { }

  ngOnInit() {
    this.service.getVar().subscribe((data) => {
     console.log(data);
   } )
  }

  onSubmit() {
     this.service.insertData(this.age);
  }
}

HTML

    <form (submit)="onSubmit()">
   <div class="form-group">
    <label>Age</label>
      <input type="numer" class="form-control" [(ngModel)]="age" age="age">
   </div>
   <input type="submit" class="btn btn-success" value="Submit">
</form>