【问题标题】:Angular 2 Two Way binding between components using Service使用服务的组件之间的Angular 2双向绑定
【发布时间】:2018-10-31 19:41:31
【问题描述】:

我需要将一个对象从组件传递到服务并由另一个组件作为可观察对象获取,以便将来当我在问题组件中更改某些内容时,它会更新服务,但目前 getQuestion() 不适用于问题组件。

服务:

   selectedSurvey: any;
   setQuestion(passedObject){ 
   this.selectedSurvey=  passedObject;
   }

   getQuestion(): Observable<any>{
  return this.selectedSurvey;
   }

调查组件

   private subscription: Subscription;
   survey: any;
  onChange(surveyObject) {
    this.surveyService.setQuestion(surveyObject);

  }

  ngOnInit() {
   this.subscription =  this.surveyService.getSurveys().subscribe( survey => {  this.survey = survey });

  }

调查组件 Html

<div class="container">
    <div class="form-group">
        <label for="sel1">Select Survey:</label>
        <select class="form-control" [(ngModel)]="selectedObject" id="selsurvey" (ngModelChange)="onChange($event)">
          <option *ngFor="let s of survey" [value]="s">{{s.surveyName}}</option>

        </select>
      </div>
</div>

问题组件

  private subscription: Subscription;
    survey: any;
   constructor(private surveyService: SurveyService) { }

     ngOnInit() {
       this.subscription =  this.surveyService.getQuestion().subscribe( survey => { console.log(survey),this.survey = survey })
      }
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    在役:

    yourSubject:Subject<WhatevaTypeYouWant>=new Subject<WhatevaTypeYouWant>();
    

    在生产者中

    service.yourSubject.next(value);
    

    在消费者中

      service.yourSubject.subscribe(val=>{handler});
    

    【讨论】:

      【解决方案2】:

      这里有一个工作示例:https://stackblitz.com/edit/angular-3anuot

      检查child-component/child-component.tschild-component/communication.service.tsapp.component.ts

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-04
        • 2016-07-14
        • 2017-03-17
        • 2019-12-10
        • 1970-01-01
        • 2017-02-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多