Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48984

Return an Observable by using a Storage value + Good practices advices

$
0
0

Hey guys !

I’m quite new with Ionic, and Django, but I’m trying my best.
I’m currently struggling with something, and I would like to have good practice before implementing weird stuff everywhere in my project.

I have a Django backend, which returns a JSON object as follow, on GET /users/{username} :

{
"id":3,
"username":"admin",
"email":"admin@example.com",
"is_active":true,
"date_joined":"2021-04-24T14:05:33.724350Z"
}

With following functions :
api.service.ts

getInfo() {       
        return from(Storage.get({ key: CURRENT_USERNAME }).then(data => {
            const userName = data.value
            console.log("url : " + `${environment.api_url}/users/${userName}`)
            return this.httpClient.get(`${environment.api_url}/users/${userName}`)
        })
        )
    }

profile.page.ts

async getInfo() {
    this.apiService.getInfo().subscribe(
      data => {
        console.log("my data stringified " + JSON.stringify(data))
        data.subscribe(data2 => {
          console.log("data 2 json " + JSON.stringify(data2))
        })
      },
      err => {
        // Set the error information to display in the template
        console.log(`An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`)
      }
    );

Sevaral questions :

  • Am I right using a Storage object to store the username ? Or should I not bother, and use a global variable, which would simplify the whole code.
  • As you can see in my profile.page.ts, the code is promise into observable which is quite horrible to read and I’m pretty sure not optimized. But, I didn’t find any way to return the correct information in my api.service.ts getInfo() method. I wanted to assign a variable to the value of my CURRENT_USERNAME, but without using a global variable, I don’t achieve to.

Thank you! Any tips, good practice, and advice would be much appreciated.

Jules

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 48984

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>