Wednesday, 12 April 2017

Display details of logged in user using MEAN stack

Pretty new to developing using the MEAN stack so bare with me.

Trying to display details of a user once they are logged in i.e. first name for now (will display last name and email later), but keep getting an undefined in the console log

At the moment I have the following in my auth.service.ts file:

profile() {
    if(this.isLoggedIn()){
        console.log('logged in');
        return this.http.get('http://localhost:3000/user/profile')
            .map((response: Response) => {
                console.log(response.json());
            })
            .catch((error: Response) => Observable.throw(error.json()));
    } else {
        console.log('not logged in');
    }       
}


Then in my user.js (routes) file, I have the following:
router.get('/profile', function (req, res, next) {
    User.findById(req.params._id, function (err, user) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
    }

    res.status(200).json({
        message: 'Success',
        obj: user
    });
});
});    


Followed by calling the profile method from the auth service in my profile.component.ts file:

export class ProfileComponent {
    @Input() user: User;

    constructor(private authService: AuthService) { }

    ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.profile()
                .subscribe(
                    data => console.log(data),
                    error => console.error(error)
                );
        }
    }
}


Here is where I get an "trying to find firstName of undefined" when trying to use
in my profile.component.html:

<div>
    hello
</div>
<div>   
    
</div>


If anyone could provide any help or pointers on how to solve this, then I will eternally be grateful!



via dumillionaire

No comments:

Post a Comment