1
编辑:为什么它的价值,我已经了解到SharedService正在初始化两次。我怀疑我正在使用单独的实例,这就是为什么.subscribe()仅限于启动器的原因。我不知道如何纠正这个......我以为Angular2中的所有东西都是单身人士?在Angular2中共享一个observable /主题
我有两个组件。我希望任何一个组件都能够通过服务进行POST,并让这两个组件都能收到响应。
这两个组件是非常基本的,并且对于这个问题的演示基本相同。真的没什么大在这里看到,但在这里,他们是以防万一:
富组件
@Component({
selector: "foo",
providers: [SharedService]
})
export class FooComponent {
constructor(private _api:API, private _service:SharedService) {
this._service.data$.subscribe(
response => console.log("FOO!", response)
// error not required here since the service handles it for all dependents.
);
}
doSomething(values) {
this._service.post(values);
}
}
栏组件
@Component({
selector: "bar"
})
export class BarComponent {
constructor(private _api:API, private _service:SharedService) {
this._service.data$.subscribe(
response => console.log("BAR!", response)
// error not required here since the service handles it for all dependents.
);
}
doSomething(values) {
this._service.post(values);
}
}
的SharedService是我一直在努力把事情做好。
@Injectable()
export class SharedService {
private _observer: Observer<Response>;
public data$;
// i wrapped Http in an API service. it does the following:
// 1. convenience methods like .map() for the observables
// 2. adding headers to every request so that i don't need to do that for every service
// 3. takes the first parameter e.g. "login" and converts it to a full endpoint
// 4. converts the "values" object in to a body string
constructor(private _api: API) {
this.data$ = new Observerable(observer = this._observer = observer).share();
}
post(values:IValues) {
this._api.post("foobar", values).subscribe(
response => this._observer.next(response),
error => console.log("foobar failure", error);
);
}
}
无论我尝试什么,我只得到调用组件的成功条件。所以如果我从“Foo”触发服务,我会得到“FOO!”如果我从“酒吧”调用它,我会得到“酒吧!”。
理想情况下,我可以从“Foo”调用它并接收“FOO!”和“BAR!”。这些回应的顺序并不重要。