ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of null (Ionic Angular)

Issue

In my angular ionic project, when I log in the first page gives me the error "ERROR Error: Uncaught (in promise): TypeError: Cannot read property ‘subscribe’ of null" but when I reload the page I don’t have the error and I have the data. thank you

    (await this.pageService.getAllTables()).subscribe((res: any) => {
          this.tables = res.body
    });
  }```

    ```getAllTables() {
        this.storage.get('USER').then(user =>{this.user = user;});
        return this.storage.get('ACCESS_TOKEN').then(token =>{
            if (this.user) {
                return this.http.get(this.url + 'table/' + this.user.id, { 
                    headers: new HttpHeaders({
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }), 
                    observe: 'response'
                });
            }
            return null;
        });
    }```

Solution

try this

getAllTables() {
        return this.storage.get('USER')
           .then(user =>{this.user = user;})
           .then(() => this.storage.get('ACCESS_TOKEN'))
           .then(token =>{
             if (this.user) {
                return this.http.get(this.url + 'table/' + this.user.id, { 
                    headers: new HttpHeaders({
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }), 
                    observe: 'response'
                });
            }
            return null;
        });

this code is still strange, as you return observable, wrapped in promise but at least is should work.

you could try to convert everything to promises. it would look like this:

getAllTables() {
        return this.storage.get('USER')
           .then(user =>{this.user = user;})
           .then(() => this.storage.get('ACCESS_TOKEN'))
           .then(token =>{
             if (this.user) {
                return this.http.get(this.url + 'table/' + this.user.id, { 
                    headers: new HttpHeaders({
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }), 
                    observe: 'response'
                }).toPromise();
            }
            return null;
        });

usage:

this.tables = (await this.pageService.getAllTables())?.body;

Answered By – Andrei

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published