使用Service在组件之间进行Angular 2双向绑定

时间:2018-10-31 19:41:32

标签: angular typescript

我需要将对象从组件传递到服务,并以可观察的方式由另一个组件获取,以便将来在我对Question Component进行更改时,它会更新Service BUT,而getQuestion()不适用于Question Component。

服务:

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

2 个答案:

答案 0 :(得分:1)

在使用中:

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

在生产者中

service.yourSubject.next(value);

在消费者中

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

答案 1 :(得分:0)

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

选中child-component/child-component.tschild-component/communication.service.tsapp.component.ts

希望有帮助