Rohit Azad Malik
Rohit Azad Malik

Reputation: 32202

how to pass data service into components in angular 5

I'm requesting from api to get data in service, but don't got how to get those data at components? I have tried to google but didn't found any solutions.

service file

login(email:string, pwd:string):void{
  this.loginModule.verifyEmailLogin(email, pwd, (data)=>{
    console.log('user login data==>, ',data)
    return data;
  })
}

Here I got to data in my console

componets file js

saveLoginForm() :void{
  //console.log(this.loginForm);
  console.log('Saved: ' + JSON.stringify(this.loginForm.value));
  this._userAuthService.login(this.loginForm.value.userEmail, this.loginForm.value.userPwd)

}

Upvotes: 0

Views: 67

Answers (2)

J. Pinxten
J. Pinxten

Reputation: 307

Assuming that your loginModule.verifyEmailLogin returns the observable from your http call

service file

login(email:string, pwd:string): Observable<any>{
    return this.loginModule.verifyEmailLogin(email, pwd, (data))
}

componets file js

saveLoginForm() :void{
    this._userAuthService.login(this.loginForm.value.userEmail, this.loginForm.value.userPwd)
       .subscribe(
           (data) => console.log(data),
           (error) => console.log(error)
       )

  }

Upvotes: 0

Pengyy
Pengyy

Reputation: 38209

You can create and return a Promise to resolve the data in callback of this.loginModule.verifyEmailLogin.

login(email:string, pwd:string): Promise<any>{
  return new Promise<any>(resolve => {
    this.loginModule.verifyEmailLogin(email, pwd, (data)=>{
      console.log('user login data==>, ',data)
      //return data;
      resolve(data);
    });
  });
}

Then get the resolved data at component via Promise.then

this._userAuthService.login(this.loginForm.value.userEmail, this.loginForm.value.userPwd).then(data => {
  // deal anything with the data
})

Return an Observable will also solve the problem.

Upvotes: 2

Related Questions