我有一个数据服务,通过HTTP运行查询(由某个组件触发),然后通过Observable
公开结果。其他组件将订阅Observable
并更新他们对结果的看法。RxJS/Angular2:为什么我的主题订阅者未被调用?
无论如何,这是主意,但它不工作。这是我的代码。
ItemListDataService:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable, Subject } from "rxjs";
import 'rxjs/add/operator/map';
@Injectable()
export class ItemListDataService {
private issues$: Subject<any>;
constructor(private http: Http) {
this.issues$ = new Subject();
this.issues$.subscribe(x => console.log('GOT IT', x));
}
getList(): Observable<any> {
return this.issues$;
}
refresh() {
this.http.get('/whatever')
.map((response: Response) => response.json())
.subscribe(data => this.issues$.next(data));
}
}
ItemListComponent:
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { ItemListDataService } from './item-list-data-service';
@Component({
selector: 'app-item-list',
templateUrl: './item-list.component.html',
styleUrls: ['./item-list.component.css'],
providers: [ItemListDataService]
})
export class ItemListComponent {
data: any;
constructor(itemListDataService: ItemListDataService) {
itemListDataService.getList().subscribe(data => {
console.log('DATA CHANGED');
this.data = data;
}, err => {
console.log('ERR', err)
},() => {
console.log('DONE');
});
}
}
在ItemListDataService.constructor
创建的用户被调用每次refresh()
被调用时。唯一不起作用的是组件中的订阅 - 既没有在那里调用回调。
我在做什么错?
Woo调用refresh()?它从哪里得到ItemListDataService?您已将ItemListDataService添加到ItemListComponent的提供者,以便组件(及其子组件)将获得自己的服务实例,与其他组件不同。 –
@JBNizet谢谢,经过一番研究,我得出了同样的结论。事实上,问题是每个组件都有自己的服务实例。来自Angular 1(和许多其他的DI框架),我期待他们是单身人士。活到老,学到老。 :-) 随意张贴,作为答案。 –