【发布时间】:2017-10-11 23:30:31
【问题描述】:
为此我尝试了很多方法,但似乎没有任何帮助。
我要完成的工作:
- 用户单击选择组件视图上的按钮
- 事件触发,在选择组件上调用
changePage() - 这会在服务上调用
changePage()并传入一个字符串 -
服务中的
changePage()更新observable - 在主组件中,创建一个
subscription,并根据服务中的Observable更改变量pageName的值 -
pageName更新为页面上的标题
服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs';
@Injectable()
export class PageService{
pageChange$: Subject<String> = new BehaviorSubject("About Me");
constructor(){
}
public changePage(changeTo: String){
console.log(changeTo); // LOGS PROPERLY
this.pageChange$.next(changeTo);
}
}
选择组件
export class SelectionComponent implements OnInit {
constructor(private _pageService:PageService) { }
ngOnInit() {
}
// Called on button click, passed a string from the button
changePage(changeTo: string){
this._pageService.changePage(changeTo);
}
}
主要组件
import { Component, OnInit } from '@angular/core';
import { PageService } from '../page-service.service';
import { AsyncPipe } from '@angular/common';
@Component({
selector: 'app-main-content',
templateUrl: './main-content.component.html',
styleUrls: ['./main-content.component.css'],
providers: [PageService]
})
export class MainContentComponent implements OnInit {
pageName: String;
constructor(private _pageService: PageService) {
}
ngOnInit() {
this._pageService.pageChange$.subscribe(value => {
console.log(value); // DOES NOT LOG
this.pageName = value;
});
}
要更新的信息
<h3 class="content-header">{{ pageName }}</h3>
我已经为此苦苦挣扎了一段时间。诚然,我对 Angular 很陌生,也许我只是对 Observables 的工作原理感到困惑,但目前它不起作用。
我在控制台中获得了一个带有“关于我”的 console.log,但之后就没有了。没有错误,什么都没有。 h3 会说 About Me,但不会改变。
【问题讨论】:
-
我们可以看到模板中的绑定(您执行点击的位置)吗?
-
我现在不在我的电脑附近,但它是 (click)="changePage('button value')"
标签: angular rxjs observable angular2-observables