【发布时间】:2020-05-11 11:02:27
【问题描述】:
所以有一个使用 Ionic/Angular 创建的简单应用程序。
app.component.html(菜单)包含用户电话:
<span *ngIf="phone">{{phone}}</span>
还有app.component.ts:
public phone: string = ''
initializeApp() {
this.platform.ready().then(() => {
this.getUser()
});
}
getUser() {
if(this.auth.isLoggedIn) {
this.auth.getUser()
.subscribe(
user => {
this.phone = user.phone
}
)
}
}
AuthService:
public isLoggedIn: boolean = false
public token: string = null
getUser(): Observable<User> {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Token': this.token
})
return this.http
.get<User>(this.util.API_URL + '/user', { headers } )
.pipe(
map(
res => {
// api returns json response with 'result' object
return res['result']
}
)
)
}
问题 应用启动时,我需要从 app.component.ts 调用 getUser() 方法。如果用户已登录,它现在可以工作。 但是当用户未登录时,我需要在用户登录成功后调用 getUser() 方法。但是,例如,我不能在 LoginComponent 的 initializeApp() 之前调用 AppComponent。
那么,在 AppComponent 中显示用户数据的正确方法是什么?
【问题讨论】:
-
成功登录后为什么不在
LoginComponent中将其设置为服务值并在AppComponent上获取它?为什么要对服务器进行冗余调用以获取用户详细信息
标签: angular ionic-framework observable