EDIT:SharedServiceが2回初期化されていることを知りました。私は個別のインスタンスで作業していると思われます。その理由は、.subscribe()がイニシエータだけに限定されているからです。私はこれを修正する方法を知らない...私はすべてがAngular2のシングルトンだと思った?Observable/SubjectをAngular2で共有する
私は2つのコンポーネントを持っています。いずれかのコンポーネントがサービスを介してPOSTできるようにし、両方のコンポーネントに応答を受け取らせたい。
2つのコンポーネントはかなり基本的であり、この問題のデモのために本質的に同じです。彼らは念のためにしているここで、ここで見ることが本当に大きな何が、私は物事が権利を取得しようとしてきたところ
Fooのコンポーネント
@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!" 「Bar」から呼び出すと、「BAR!」と表示されます。
理想的には、「Foo」から呼び出すことができ、「FOO!」を受け取ることができます。と "バー!"これらの反応の順序は、実際問題ではありません。
@Component({
selector: "foo",
providers: [SharedService] // only existed on one of them
})
@Component({
selector: "bar"
})
2つのインスタンスを作成した: