【发布时间】:2016-06-26 23:06:59
【问题描述】:
我对 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); }
在此之后,当我控制台记录“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);
这是为什么呢?
【问题讨论】:
标签: angularjs typescript publish-subscribe rxjs observable