Angular Get请求在组件请求订阅服务器时返回订阅服务器
get请求自身工作,如果我打印请求的结果,它将返回json,但当我访问组件中的方法时,该方法将重新运行订阅,并且我设置的变量保持未定义 身份验证服务:Angular Get请求在组件请求订阅服务器时返回订阅服务器,angular,typescript,ionic-framework,Angular,Typescript,Ionic Framework,get请求自身工作,如果我打印请求的结果,它将返回json,但当我访问组件中的方法时,该方法将重新运行订阅,并且我设置的变量保持未定义 身份验证服务: getUserData() { return this.http.get(`${this.env.API_URL}/users/firebase/${JSON.parse(localStorage.getItem('user')).uid}`).subscribe({ next: ( data:any ) => {
getUserData() {
return this.http.get(`${this.env.API_URL}/users/firebase/${JSON.parse(localStorage.getItem('user')).uid}`).subscribe({
next: ( data:any ) => {
console.log(data.data.person)
},
error: error => {
this.alert.showAlert("Error!", error.message)
console.error('There was an error!', error)
}
})
}
user:any
constructor(public auth: AuthService, private router: Router, private alert: Ion_Alert) {
if(this.auth.isLoggedIn) {
this.user = this.auth.getUserData()
console.log(this.user)
} else {
this.alert.showAlert('Error!', "You're not logged in or you haven't verified your mail")
}
}
帐户组件:
getUserData() {
return this.http.get(`${this.env.API_URL}/users/firebase/${JSON.parse(localStorage.getItem('user')).uid}`).subscribe({
next: ( data:any ) => {
console.log(data.data.person)
},
error: error => {
this.alert.showAlert("Error!", error.message)
console.error('There was an error!', error)
}
})
}
user:any
constructor(public auth: AuthService, private router: Router, private alert: Ion_Alert) {
if(this.auth.isLoggedIn) {
this.user = this.auth.getUserData()
console.log(this.user)
} else {
this.alert.showAlert('Error!', "You're not logged in or you haven't verified your mail")
}
}
返回
只有在调用调用服务的方法时,才应
subscribe
:
this.auth.getUserData().subscribe({
( data:any ) => {
this.user = data.data.person // <-- I think you mean this
console.log(data.data.person)
},
error: error => {
this.alert.showAlert("Error!", error.message)
console.error('There was an error!', error)
}
})
}
身份验证服务:
getUserData() {
return this.http.get(`${this.env.API_URL}/users/firebase/${JSON.parse(localStorage.getItem('user')).uid}`)
}
以及,在组件的构造函数中(注入服务的位置):
this.auth.getUserData().subscribe({
(数据:任何)=>{
this.user=data.data.person//{
this.alert.showAlert(“Error!”,Error.message)
console.error('发生错误!',error)
}
})
}