nicknack123123
nicknack123123

Reputation: 115

Why Observer is undefined

At the constructor I am creating the Observable and Observer. Then trying to send next() method in apiConnect() ends in an Exception.

The service will be bootstrapped to be available over my whole application.

    private _apiServerConnected: boolean = false;
public _apiServerConnectedObserver: Observer<boolean>;
public apiServerConnectedObservable: Observable<boolean>;

private _serverIdx = 0;
private _apiServers: Array<string> = ['localhost:81', '192.168.2.210:81', '172.17.32.164:81'];
private _server: string;

constructor(
    private _http: Http,
    private _apiCalls: ApiCalls
) {
    this._server = this._apiServers[0];

    // attach and create observer and observable for apiserverconnected
    this.apiServerConnectedObservable = new Observable(observer => this._apiServerConnectedObserver = observer)
        .startWith(this._apiServerConnected)
        .share();

    this.apiConnect();
}

apiConnect() {
    this._http.get('http://' + this._server + this._apiCalls.SysConnect())
        .map((res) => res.json())
        .subscribe((data) => {
            this._apiServerConnected = data;

            if (this._apiServerConnected) {
                this.apiServer = 'http://' + this._server;
                console.log('Server connected: ' + this._server);
                this._apiServerConnectedObserver.next(this._apiServerConnected);
            } else {
                this.apiConnectError();
            }
        }, (error) => {
            this.apiConnectError();
        }, () => {
        });
}

apiConnectError() {
    this._serverIdx++;
    if (this._serverIdx > this._apiServers.length) {
        this._serverIdx = 0;
    }
    this._server = this._apiServers[this._serverIdx];
    console.log('Server connection failed trying next: ' + this._server);
    this.apiConnect();
}

EXCEPTION: TypeError: _this._apiServerConnectedObserver is undefined

Any ideas?

Upvotes: 2

Views: 2560

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202246

You need to subscribe on the apiServerConnectedObservable observable to initialize it. Otherwise the initialization callback is never called and the observer never initialized.

this.apiServerConnectedObservable
  = new Observable(observer => this._apiServerConnectedObserver = observer)
    .startWith(this._apiServerConnected)
    .share();

this.apiServerConnectedObservable.subscribe(() => {
  (...)
});

Upvotes: 3

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657691

Here

this._apiServerConnectedObserver.next(

you access the variable but it is never initialized.

Upvotes: 1

Related Questions