Get请求在组件请求时返回subscriber



get请求本身工作,如果我打印请求的结果,它会按原样返回json,但当我访问组件中的方法时,该方法会重新运行订阅,并且我设置的变量仍然未定义。

身份验证服务:

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")
}
}

返回

//console.log(this.user)
Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, …}
closed: true
destination: SafeSubscriber {closed: true, _parentOrParents: null, _subscriptions: null, syncErrorValue: null, syncErrorThrown: false, …}
isStopped: true
syncErrorThrowable: true
syncErrorThrown: false
syncErrorValue: null
_parentOrParents: null
_subscriptions: null
__proto__: Subscription
//console.log(data.data.person)
{id: 35, address: null, dni: "343242342ds", document_type: 1, phone: "12424134234", …}
address: null
city_id: 215
dni: "343242342ds"
document_type: 1
documents_type: {id: 1, name: "CEDULA DE CIUDADANIA", status: 1}
first_name: "asdasdasdad"
genre: "male"
id: 35
last_name: "asdasdasdasd"
municipio: {id: 215, name: "TUNJA", departamento_id: 5, departamento: {…}}
phone: "12424134234"
photo: null
profession: "fdsdsfsdf"
user_id: "57"
__proto__: Object

当您调用调用服务的方法时,应该只使用subscribe

身份验证服务

getUserData() { 
return this.http.get(`${this.env.API_URL}/users/firebase/${JSON.parse(localStorage.getItem('user')).uid}`)
}

并且,在组件的constructor中(注入服务的位置(:

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)
}
})
}

最新更新