My goal is to display the logged-in user’s name.
I have a back-end Express service that successfully uses Mongoose to perform MongoDB queries. I’m able to see it work with Postman. This service queries a “users” collection in the database. It takes a userId and returns the user’s firstName.
I’m encountering problems implementing an Angular2 front-end service that gets the userId
from local storage, passes it to the back-end, and retrieves the user’s firstName
. Then I want to use Handlebars string interpolation to insert the username wherever I want.
loggedInUser()
in the code below is where I'm currently focusing.
auth.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs';
import { User } from './user.model';
import { ErrorService } from '../errors/error.service';
@Injectable()
export class AuthService {
constructor(private http: Http, private errorService: ErrorService) {}
loggedInUser() {
const userId = localStorage.getItem('userId');
console.log('Service) User ID:' + userId);
return this.http.get('htp://localhost:3000/user/current/' + userId)
.map((response: Response) => {
const user = response.json().obj;
return user;
})
};
When I try to use loggedInUser in a component's HTML file, I get no output when the route is rendered. The console.log call produces nothing in the browser's console; it's as if the method isn't being called.
signup.component.html
Username: {{ loggedInUser }}