Get 请求在组件请求时返回订阅者

时间:2021-01-12 17:38:41

标签: angular typescript ionic-framework

get 请求自己工作,如果我打印请求的结果,它会按原样返回 json,但是当我访问组件中的方法时,该方法会重新调整订阅,而我设置的变量仍然未定义。< /p>

身份验证服务:

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

1 个答案:

答案 0 :(得分:1)

您应该只在调用调用服务的方法时使用 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)
      }
    })
  }
相关问题