可观察 - 多个子纤维

时间:2016-03-11 16:00:19

标签: angularjs typescript publish-subscribe rxjs observable

我是RxJS和Observables的新手。我按照本教程 - >

https://coryrylan.com/blog/angular-2-observable-data-services

我的问题是,

有:

  

OnePage :操纵并显示答案

     

服务:保持相同的答案

     

SecondPage :操纵并显示答案

在该链接中,他将数据订阅到组件数据,如下所示

  

ngOnInit(){       todosService.todos $ .subscribe(updatedTodos => this.componentTodos = updatedTodos);       todosService.loadTodos(); }

是我的,是

onPageWillEnter(){
    this.service.answers$.subscribe(updatedAnswers => {
        this.answers = updatedAnswers;
        console.log("we subscribed from questions");
    });
    this.service.load().then((rootobject:RootObject) =>{
        this.rootobject = rootobject;
        this.questions = rootobject.Item.questions;
        this.current_question = this.service.current_question;
        this.pushNextImage(0);
        console.log(this.answers, " Questions page loaded => then");
    });
    console.log(this.answers, " Questions page loaded");
}

一切都很酷。我可以更新全局“答案”和我当地的“答案”,如下所示。

markQuestion(event){
   this.current_question = this.questions[event.q_number];
   this.current_question_number = event.q_number;
   //Mark the answer in answers
   this.answers[event.q_number-1] = event.val;
   this.service._answersObserver.next(this.answers);
}

在此之后,当我在console.log中“service.answers”时,它会被更新,但是还是。

在第二页:

onPageWillEnter(){
      this.service.answers$.subscribe(updatedAnswers => {
          this.answers = updatedAnswers;
          console.log("we subscribed from questions");
      });
      //this.service._answersObserver.next(this.service.answers);
      console.log(this.service.answers$);
      console.log(this.service.answers," Page loaded AnswerSheet" , this.answers ," => answer_list");
  }

它甚至没有进入订阅事件。没有东西在控制台里。但是我这样做了:

this.service._answersObserver.next(this.service.answers);

为什么?

这里是plunker https://plnkr.co/edit/c3fu5hsPZXslLegdeD0p?p=info

1 个答案:

答案 0 :(得分:0)

如果您在this.service.answers$.subscribe类的构造函数中添加AnswerSheetPage而不是onPageWillEnter方法,是否有效?