0

Using MongoDB, express.js, angular4, node.js

A string I retrieve is well retrieved, but not the same as a full object...

account.service.ts (full, )

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
const jwtDecode = require('jwt-decode');

import { User } from '../../models/user.model';
import { AuthService } from './auth.service';


@Injectable()
export class AccountService {
  constructor(private http: HttpClient,
              private authService: AuthService) {}

  user: any[];

  currentUser() {
    if(this.authService.isAuthenticated()){
      const token = localStorage.getItem('token');
      const decoded = jwtDecode(token);
      return decoded.user;
    }
  };

 getProfile() {
const id = this.currentUser();
return this.http.get("http://localhost:3000/user/" + id).
  map(
  (response: Response) => {
    const data = response.json();
    return data;
  }
)
  .catch(
    (error: Response) => {
      console.log(error);
      return Observable.throw(error.json());
    }
  )
}

user-profile.component.ts

export class UserProfileComponent implements OnInit {
  id: string;
  user: any;

  constructor(private account: AccountService) {}

  ngOnInit() {
    this.id = this.account.currentUser();
    this.user = this.account.getProfile()
      .subscribe(user => {
              this.user = user;
              return this.user;
            });
  }

  logUser() {
    console.log(this.id);
    console.log(this.user);
  }
}

user-profile.component.html

  <p>{{user}}</p>
  <p>User with ID {{id}} Loaded</p>
  <a (click)="logUser()">Log User Test</a>

HTML file shows:

[object Object]

User with ID 59ca916323aae527b8ec7fa2 Loaded

What I get from clicking "log User" link is the retrieved ID string and the user object:

59ca916323aae527b8ec7fa2 [{...}] //clicking this reveals all of the object's details.

But I can't make that step of getting those details and presenting them in the HTML as I successfully managed with the ID... I mean, {{user.anything}} doesn't fetch the user's data as it should

May I have some assistance?

2
  • could you please show your full AccountService class? Commented Sep 26, 2017 at 23:44
  • Yeah, I have added the full class. Commented Sep 26, 2017 at 23:55

1 Answer 1

1

Change your getProfile() to,

getProfile() {
    const id = this.currentUser();
    return this.http.get("http://localhost:3000/user/" + id).
      map(
      (response) => response.json()
    )
      .catch(
        (error: Response) => {
          console.log(error);
          return Observable.throw(error.json());
        }
      )
    }

Also, in ngOnInit() change this one,

this.user = this.account.getProfile()
      .subscribe((user) => {
              this.user = user;
            });

See if it gives you the right output.

EDIT

Change this one,

this.user = this.account.getProfile()
          .subscribe((user) => {
                  this.user = JSON.parse(JSON.stringify(user));
                });

EDIT-2

this.user = this.account.getProfile()
              .subscribe((user) => {
                      this.user = JSON.stringify(user);
                      this.userObj = JSON.parse(JSON.stringify(user));
                      // also try, this.userObj = user; if above line didn't work
                    });

Define another property in component as ,

userObj: any;

Refer to the object in template as this

{{ userObj[0]?.email }}
Sign up to request clarification or add additional context in comments.

15 Comments

Thank you for replying. It works just like before - in the user-profile component "LogUser" successfully prints out the ID, and the user object is also retrieved inside the [{..}] Object (hovering above it says "Object")
Try this on the template: <p>{{ user | json }}</p>. (using json pipe)
This changed the html output from [object Object] to [ { "_id": "59ca916323aae527b8ec7fa2", "gender": "male", "birthday": "2017-09-07", "email": "[email protected]", "password": "hashed.password", "__v": 0, "name": { "firstName": "name", "middleName": "test", "lastName": "name" } } ] And also supplied an error: TypeError: Converting circular structure to JSON
apart from the error, is that what you are looking for?
It seems like the right direction... to ngOnInit I added: this.user = JSON.stringify(user), then on HTML: {{user}} gives the same result as the piped result, except there is no error now, but {{user.email}} for instance is still not being displayed...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.