0

In my code I have custom post method that extents the http class of angular 2.

post(url: string, body: string, options?: RequestOptionsArgs): Observable<any> {

        if (!this._gs.externalRequest) {
            let that = this;
            this._gs.getToken().then((token) => {
                if (token) {
                    options = this.prepareOptions(options, token);
                }
                return that.sendPostRequest(url, body, options);
            });
        }
        else {
            this._gs.externalRequest = false;
            return this.sendPostRequest(url, body, options);
        }
    }

In above code post method returns an Observable whereas the method this._gs.getToken() in if condition reads token from the local storage its an asynchronous call and returns a promise.

Though the compilation doenst generate any error but, when I access

this.http.post('/api/myFormHandler', this.form.value) .subscribe((data) => { });

class MyFormComponent- inline template:16:29 caused by: Cannot read property 'subscribe' of undefined
Naveed Ahmed
  • 10,048
  • 12
  • 46
  • 85

1 Answers1

1

Due to async nature of the JS, your first condition doesn't actually return the correct thing. To be able to return Observable<any> from the post method, you should modify the body of your first if to work with two observables that depend on each other.

// sample 
const getToken = Promise.resolve('token');
const resolveToken = Rx.Observable.fromPromise(getToken);

...
if (!this._gs.externalRequest) {
  return resolveToken
     .flatMap(token => {
        if (token) {
           options = this.prepareOptions(token);
        }
        return this.sendPostRequest(url, options);
     })
}
...
this.post.subscribe(console.log);

Firstly, you have to cast your token returning method to a observable and then flatMap it as we need this result in a second observable.

Please, refer to this article - combining observables.

Daniel Mylian
  • 732
  • 6
  • 12