如何在Angular中设置服务的输入模型值?

时间:2016-08-02 17:51:35

标签: angular

此问题是如何从Angular 2中的服务设置输入模型值。

这是我的示例代码:
成分:

//our root app component
import {Component} from 'angular2/core'
import {Service} from './service'

@Component({
  selector: 'my-directive',
  providers: [],
  template: `<input [(ngModel)]="abc">`,
  directives: []
})
export class Directive {
  constructor(public service: Service) {
    this.abc = this.service.value;
  }
}

服务:

//我们的根应用程序组件 从'angular2 / core'导入{Injectable}

@Injectable()
export class Service {
  constructor() {
    this.value = "service"
  }
  abcFun(){
    // need to update value from here
  }
}

plunkr here

2 个答案:

答案 0 :(得分:3)

试试这个:

<强> component.html

<input type="text" [(ngModel)]="abc">

<强> component.ts

private abc: string;

constructor(
        public homeService: HomeService
    ) { }
ngOnInit() {
        this.abc = this.homeService.value;
    }

<强> component.service.ts

public value: string;

constructor(private http: Http) { 
        this.value = "Hello world";
    }

答案 1 :(得分:0)

问题是您在Service和Controller中有不同的值实例。如果您在服务中更改value,则只更改那里的实例,控制器的实例仍然是旧实例。反过来也是这样。您可以通过将字符串存储在这样的对象中来解决此问题。

@Injectable()
export class Service {
  data = { value: '' };
  constructor() {
    this.data.value = "service"
  }
}

@Component({
  selector: 'my-directive',
  providers: [],
  template: `<input [(ngModel)]="abc.value">`,
  directives: []
})
export class Directive {
  constructor(public service: Service) {
    this.abc = this.service.data;
  }
}

另一种解决方案是如https://github.com/DanielYKPan/date-time-picker/blob/master/src/picker.component.ts所示设置与可观察对象的通信。

@Injectable()
export class Service {
  valueSource = new Subject<string>();
  value$ = this.valueSource.asObservable();
  updateValue(value: string) {
    this.valueSource.next(value);
  }
}

@Component({
  selector: 'my-directive',
  providers: [],
  template: `<input [(ngModel)]="value">`,
  directives: []
})
export class Directive {
  value: string;
  constructor(public service: Service) {
    this.service.value$.subscribe(value => this.value = value);
  }
}