TransWikia.com

How to get one data from database by id (MEAN Stack)?

Stack Overflow Asked by Dorottya Burmeister on December 16, 2021

I am creating an application in MEAN stack where you can upload properties to sell and rent. I want to create a page for every single uploaded property. For this, I need to get that property by id from the database. I can get it on the backend server, but I can’t see it on the frontend. I upload the code, so you can understand it better.

the backend code, user.js

router.get("/:id", (req, res, next) => {
  let loggedInUser;
  User.findById(req.params.id).then(user => {
    if (user) {
      loggedInUser = user;
      console.log(loggedInUser);
      res.json({
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        phone: user.phone,
        image: user.image,
        jobTitle: user.jobTitle
      });
    } else {
      res.status(404).json({ message: "User not found!" });
    }
  });
});

in the auth.service.ts

private userData: LoggedInUser;

getUser(id: string){
    let loggedInUser: LoggedInUser;
    this.http.get<{user: any}>("http://localhost:3000/api/user/" + id)
    .subscribe(response => {
      loggedInUser = response.user;
      this.userData = loggedInUser;
    });
    console.log(this.userData);
  }

Here I got undefined when I console.log it.

I just run the getUser method in the userhome.component.ts.

ngOnInit() {
    this.authService.getUser(this.id);
  }

I would really appreciate any help!

One Answer

Since you have declared the object representation that matches the endpoint response, this code snippet should work perfectly fine. I suggest you try it out.

private userData: LoggedInUser;

getUser(id: string) {
  this.http.get < LoggedInUser > ("http://localhost:3000/api/user/" + id)
    .subscribe(response => {
      this.userData = response.user;
      console.log(this.userData);
    });

}

Answered by Sunkanmi Ijatuyi on December 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP