【发布时间】:2021-05-01 14:44:31
【问题描述】:
我对 Ionic 和 Django 还很陌生,但我正在尽力而为。 我目前正在努力解决一些问题,我希望在我的项目中到处实施奇怪的东西之前有良好的实践。
我有一个 Django 后端,它在 GET /users/{username} 上返回如下 JSON 对象:
{
"id":3,
"username":"admin",
"email":"admin@example.com",
"is_active":true,
"date_joined":"2021-04-24T14:05:33.724350Z"
}
具有以下功能: 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}`)
}
);
几个问题:
- 我使用存储对象来存储用户名是否正确?或者我不应该打扰,并使用全局变量,这将简化整个代码。
- 正如您在我的 profile.page.ts 中看到的那样,该代码被承诺为可观察的,阅读起来非常糟糕,而且我很确定没有优化。但是,我没有找到任何方法在我的 api.service.ts getInfo() 方法中返回正确的信息。我想为我的 CURRENT_USERNAME 的值分配一个变量,但不使用全局变量,我无法实现。
谢谢!任何提示、良好做法和建议将不胜感激。
朱尔斯
【问题讨论】:
标签: angular ionic-framework promise rxjs observable