首页 文章

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

提问于
浏览
2

这里的问题是如何从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()
export class Service {
  constructor() {
    this.value = "service"
  }
  abcFun(){
    // need to update value from here
  }
}

plunkr here

2 回答

  • 0

    试试这个 :

    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";
        }
    
  • 3

    问题是您在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;
      }
    }
    

    另一种解决方案是设置与observable的通信,如here所示 .

    @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);
      }
    }
    

相关问题