Angular 7 Cannot read the property email of undefined [duplicate]












-2















This question already has an answer here:




  • Angular 6 - ERROR TypeError: Cannot read property 'value' of undefined

    2 answers




I just want to display the email of this logged in user in the header



Here is my AuthService:



import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../interfaces/user';

export interface Form {
email: string;
password: string;
}

@Injectable({
providedIn: 'root'
})
export class AuthService {

constructor(private http: HttpClient) { }

login(login): Observable<boolean> {
return this.http.post<{ token: string }>(
'https://megaphone-test.herokuapp.com/api/auth/login',
login)
.pipe(
map(result => {
localStorage.setItem('access_token', result.token);
return true;
})
);
}

getUser(): Observable<User> {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user',
{
headers: new HttpHeaders().append('x-access-token', token)
});
}

isAdmin() {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user/isAdmin',
{
headers: new HttpHeaders().set('x-access-token', token)
}
)
.subscribe(
res => console.log(res['isAdmin']),
err => console.log(err)
);
}

logout() {
localStorage.removeItem('access_token');
}

public get loggedIn(): boolean {
return (localStorage.getItem('access_token') !== null);
}

}


Here is my Component:



import { Component, OnInit, Input } from '@angular/core';
import { AuthService } from '../../core/services/auth.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { User } from '../../core/interfaces/user';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

user: User;

constructor(public auth: AuthService, private router: Router) { }

ngOnInit() {
this.auth.getUser()
.subscribe(
user => this.user = user
);
}

doLogout() {
this.auth.logout();
this.router.navigate(['login']);
}

}


Here is my Template:



 <div class="header-actions" *ngIf="auth.loggedIn">
<clr-dropdown>
<button class="nav-text" clrDropdownTrigger>
{{ user.email }}
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a href="..." clrDropdownItem>Preferences</a>
<a clrDropdownItem (click)="doLogout()">Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>


ERROR HeaderComponent.html:17 ERROR TypeError: Cannot read property 'email' of undefined



It seems no matter which way I code this it still never knows who the user is. I can console log it all day and it shows this logged in user no problems.



Cheers,










share|improve this question















marked as duplicate by ConnorsFan, Jeto, R. Richards, Community Nov 20 '18 at 21:11


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • I remember debugging via console.log, and though it was displaying my data fine, my program was saying it doesn't exist. I believe console.log does something along the async pipe, and can fool you into thinking that data was available.
    – Bytech
    Nov 12 '18 at 22:32










  • It is user that does not exist yet when the view is shown initially. Did you try {{user?.email}}?
    – ConnorsFan
    Nov 12 '18 at 22:32












  • yup just now. The problem is my "user" email is not a nullable property
    – Clayton Allen
    Nov 12 '18 at 22:35










  • ?. is the Angular safe navigation operator; it is not about a nullable property. What do you get with it? Do you still have an error?
    – ConnorsFan
    Nov 12 '18 at 22:36












  • @ConnorsFan is right. When the component is initialized, user will be null. Doing user?.email will solve your problem.
    – Boland
    Nov 12 '18 at 22:39
















-2















This question already has an answer here:




  • Angular 6 - ERROR TypeError: Cannot read property 'value' of undefined

    2 answers




I just want to display the email of this logged in user in the header



Here is my AuthService:



import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../interfaces/user';

export interface Form {
email: string;
password: string;
}

@Injectable({
providedIn: 'root'
})
export class AuthService {

constructor(private http: HttpClient) { }

login(login): Observable<boolean> {
return this.http.post<{ token: string }>(
'https://megaphone-test.herokuapp.com/api/auth/login',
login)
.pipe(
map(result => {
localStorage.setItem('access_token', result.token);
return true;
})
);
}

getUser(): Observable<User> {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user',
{
headers: new HttpHeaders().append('x-access-token', token)
});
}

isAdmin() {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user/isAdmin',
{
headers: new HttpHeaders().set('x-access-token', token)
}
)
.subscribe(
res => console.log(res['isAdmin']),
err => console.log(err)
);
}

logout() {
localStorage.removeItem('access_token');
}

public get loggedIn(): boolean {
return (localStorage.getItem('access_token') !== null);
}

}


Here is my Component:



import { Component, OnInit, Input } from '@angular/core';
import { AuthService } from '../../core/services/auth.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { User } from '../../core/interfaces/user';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

user: User;

constructor(public auth: AuthService, private router: Router) { }

ngOnInit() {
this.auth.getUser()
.subscribe(
user => this.user = user
);
}

doLogout() {
this.auth.logout();
this.router.navigate(['login']);
}

}


Here is my Template:



 <div class="header-actions" *ngIf="auth.loggedIn">
<clr-dropdown>
<button class="nav-text" clrDropdownTrigger>
{{ user.email }}
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a href="..." clrDropdownItem>Preferences</a>
<a clrDropdownItem (click)="doLogout()">Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>


ERROR HeaderComponent.html:17 ERROR TypeError: Cannot read property 'email' of undefined



It seems no matter which way I code this it still never knows who the user is. I can console log it all day and it shows this logged in user no problems.



Cheers,










share|improve this question















marked as duplicate by ConnorsFan, Jeto, R. Richards, Community Nov 20 '18 at 21:11


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • I remember debugging via console.log, and though it was displaying my data fine, my program was saying it doesn't exist. I believe console.log does something along the async pipe, and can fool you into thinking that data was available.
    – Bytech
    Nov 12 '18 at 22:32










  • It is user that does not exist yet when the view is shown initially. Did you try {{user?.email}}?
    – ConnorsFan
    Nov 12 '18 at 22:32












  • yup just now. The problem is my "user" email is not a nullable property
    – Clayton Allen
    Nov 12 '18 at 22:35










  • ?. is the Angular safe navigation operator; it is not about a nullable property. What do you get with it? Do you still have an error?
    – ConnorsFan
    Nov 12 '18 at 22:36












  • @ConnorsFan is right. When the component is initialized, user will be null. Doing user?.email will solve your problem.
    – Boland
    Nov 12 '18 at 22:39














-2












-2








-2








This question already has an answer here:




  • Angular 6 - ERROR TypeError: Cannot read property 'value' of undefined

    2 answers




I just want to display the email of this logged in user in the header



Here is my AuthService:



import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../interfaces/user';

export interface Form {
email: string;
password: string;
}

@Injectable({
providedIn: 'root'
})
export class AuthService {

constructor(private http: HttpClient) { }

login(login): Observable<boolean> {
return this.http.post<{ token: string }>(
'https://megaphone-test.herokuapp.com/api/auth/login',
login)
.pipe(
map(result => {
localStorage.setItem('access_token', result.token);
return true;
})
);
}

getUser(): Observable<User> {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user',
{
headers: new HttpHeaders().append('x-access-token', token)
});
}

isAdmin() {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user/isAdmin',
{
headers: new HttpHeaders().set('x-access-token', token)
}
)
.subscribe(
res => console.log(res['isAdmin']),
err => console.log(err)
);
}

logout() {
localStorage.removeItem('access_token');
}

public get loggedIn(): boolean {
return (localStorage.getItem('access_token') !== null);
}

}


Here is my Component:



import { Component, OnInit, Input } from '@angular/core';
import { AuthService } from '../../core/services/auth.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { User } from '../../core/interfaces/user';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

user: User;

constructor(public auth: AuthService, private router: Router) { }

ngOnInit() {
this.auth.getUser()
.subscribe(
user => this.user = user
);
}

doLogout() {
this.auth.logout();
this.router.navigate(['login']);
}

}


Here is my Template:



 <div class="header-actions" *ngIf="auth.loggedIn">
<clr-dropdown>
<button class="nav-text" clrDropdownTrigger>
{{ user.email }}
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a href="..." clrDropdownItem>Preferences</a>
<a clrDropdownItem (click)="doLogout()">Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>


ERROR HeaderComponent.html:17 ERROR TypeError: Cannot read property 'email' of undefined



It seems no matter which way I code this it still never knows who the user is. I can console log it all day and it shows this logged in user no problems.



Cheers,










share|improve this question
















This question already has an answer here:




  • Angular 6 - ERROR TypeError: Cannot read property 'value' of undefined

    2 answers




I just want to display the email of this logged in user in the header



Here is my AuthService:



import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../interfaces/user';

export interface Form {
email: string;
password: string;
}

@Injectable({
providedIn: 'root'
})
export class AuthService {

constructor(private http: HttpClient) { }

login(login): Observable<boolean> {
return this.http.post<{ token: string }>(
'https://megaphone-test.herokuapp.com/api/auth/login',
login)
.pipe(
map(result => {
localStorage.setItem('access_token', result.token);
return true;
})
);
}

getUser(): Observable<User> {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user',
{
headers: new HttpHeaders().append('x-access-token', token)
});
}

isAdmin() {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user/isAdmin',
{
headers: new HttpHeaders().set('x-access-token', token)
}
)
.subscribe(
res => console.log(res['isAdmin']),
err => console.log(err)
);
}

logout() {
localStorage.removeItem('access_token');
}

public get loggedIn(): boolean {
return (localStorage.getItem('access_token') !== null);
}

}


Here is my Component:



import { Component, OnInit, Input } from '@angular/core';
import { AuthService } from '../../core/services/auth.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { User } from '../../core/interfaces/user';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

user: User;

constructor(public auth: AuthService, private router: Router) { }

ngOnInit() {
this.auth.getUser()
.subscribe(
user => this.user = user
);
}

doLogout() {
this.auth.logout();
this.router.navigate(['login']);
}

}


Here is my Template:



 <div class="header-actions" *ngIf="auth.loggedIn">
<clr-dropdown>
<button class="nav-text" clrDropdownTrigger>
{{ user.email }}
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a href="..." clrDropdownItem>Preferences</a>
<a clrDropdownItem (click)="doLogout()">Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>


ERROR HeaderComponent.html:17 ERROR TypeError: Cannot read property 'email' of undefined



It seems no matter which way I code this it still never knows who the user is. I can console log it all day and it shows this logged in user no problems.



Cheers,





This question already has an answer here:




  • Angular 6 - ERROR TypeError: Cannot read property 'value' of undefined

    2 answers








angular observable string-interpolation angular-httpclient angular7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 15:48









Goncalo Peres

1,3261318




1,3261318










asked Nov 12 '18 at 22:23









Clayton Allen

808




808




marked as duplicate by ConnorsFan, Jeto, R. Richards, Community Nov 20 '18 at 21:11


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by ConnorsFan, Jeto, R. Richards, Community Nov 20 '18 at 21:11


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • I remember debugging via console.log, and though it was displaying my data fine, my program was saying it doesn't exist. I believe console.log does something along the async pipe, and can fool you into thinking that data was available.
    – Bytech
    Nov 12 '18 at 22:32










  • It is user that does not exist yet when the view is shown initially. Did you try {{user?.email}}?
    – ConnorsFan
    Nov 12 '18 at 22:32












  • yup just now. The problem is my "user" email is not a nullable property
    – Clayton Allen
    Nov 12 '18 at 22:35










  • ?. is the Angular safe navigation operator; it is not about a nullable property. What do you get with it? Do you still have an error?
    – ConnorsFan
    Nov 12 '18 at 22:36












  • @ConnorsFan is right. When the component is initialized, user will be null. Doing user?.email will solve your problem.
    – Boland
    Nov 12 '18 at 22:39


















  • I remember debugging via console.log, and though it was displaying my data fine, my program was saying it doesn't exist. I believe console.log does something along the async pipe, and can fool you into thinking that data was available.
    – Bytech
    Nov 12 '18 at 22:32










  • It is user that does not exist yet when the view is shown initially. Did you try {{user?.email}}?
    – ConnorsFan
    Nov 12 '18 at 22:32












  • yup just now. The problem is my "user" email is not a nullable property
    – Clayton Allen
    Nov 12 '18 at 22:35










  • ?. is the Angular safe navigation operator; it is not about a nullable property. What do you get with it? Do you still have an error?
    – ConnorsFan
    Nov 12 '18 at 22:36












  • @ConnorsFan is right. When the component is initialized, user will be null. Doing user?.email will solve your problem.
    – Boland
    Nov 12 '18 at 22:39
















I remember debugging via console.log, and though it was displaying my data fine, my program was saying it doesn't exist. I believe console.log does something along the async pipe, and can fool you into thinking that data was available.
– Bytech
Nov 12 '18 at 22:32




I remember debugging via console.log, and though it was displaying my data fine, my program was saying it doesn't exist. I believe console.log does something along the async pipe, and can fool you into thinking that data was available.
– Bytech
Nov 12 '18 at 22:32












It is user that does not exist yet when the view is shown initially. Did you try {{user?.email}}?
– ConnorsFan
Nov 12 '18 at 22:32






It is user that does not exist yet when the view is shown initially. Did you try {{user?.email}}?
– ConnorsFan
Nov 12 '18 at 22:32














yup just now. The problem is my "user" email is not a nullable property
– Clayton Allen
Nov 12 '18 at 22:35




yup just now. The problem is my "user" email is not a nullable property
– Clayton Allen
Nov 12 '18 at 22:35












?. is the Angular safe navigation operator; it is not about a nullable property. What do you get with it? Do you still have an error?
– ConnorsFan
Nov 12 '18 at 22:36






?. is the Angular safe navigation operator; it is not about a nullable property. What do you get with it? Do you still have an error?
– ConnorsFan
Nov 12 '18 at 22:36














@ConnorsFan is right. When the component is initialized, user will be null. Doing user?.email will solve your problem.
– Boland
Nov 12 '18 at 22:39




@ConnorsFan is right. When the component is initialized, user will be null. Doing user?.email will solve your problem.
– Boland
Nov 12 '18 at 22:39












2 Answers
2






active

oldest

votes


















0














 ngOnInit() {
this.auth.getUser()
.subscribe(
user => this.user = user['user']
);
}


On the component init






share|improve this answer

















  • 1




    If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
    – itsundefined
    Nov 12 '18 at 23:26



















0














 getUser(): Observable<User> {
const token = localStorage.getItem('access_token');
return this.http.get<User>(
'https://megaphone-test.herokuapp.com/api/user',
{
headers: new HttpHeaders().append('x-access-token', token)
}
);
}





share|improve this answer




























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














     ngOnInit() {
    this.auth.getUser()
    .subscribe(
    user => this.user = user['user']
    );
    }


    On the component init






    share|improve this answer

















    • 1




      If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
      – itsundefined
      Nov 12 '18 at 23:26
















    0














     ngOnInit() {
    this.auth.getUser()
    .subscribe(
    user => this.user = user['user']
    );
    }


    On the component init






    share|improve this answer

















    • 1




      If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
      – itsundefined
      Nov 12 '18 at 23:26














    0












    0








    0






     ngOnInit() {
    this.auth.getUser()
    .subscribe(
    user => this.user = user['user']
    );
    }


    On the component init






    share|improve this answer












     ngOnInit() {
    this.auth.getUser()
    .subscribe(
    user => this.user = user['user']
    );
    }


    On the component init







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 12 '18 at 23:15









    Clayton Allen

    808




    808








    • 1




      If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
      – itsundefined
      Nov 12 '18 at 23:26














    • 1




      If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
      – itsundefined
      Nov 12 '18 at 23:26








    1




    1




    If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
    – itsundefined
    Nov 12 '18 at 23:26




    If you had to do that, it means you had a wrong type generic on that .get() method. Change it to this.http.get<{user: User}> and next time pay extra attention to how the data comes back from the backend.
    – itsundefined
    Nov 12 '18 at 23:26













    0














     getUser(): Observable<User> {
    const token = localStorage.getItem('access_token');
    return this.http.get<User>(
    'https://megaphone-test.herokuapp.com/api/user',
    {
    headers: new HttpHeaders().append('x-access-token', token)
    }
    );
    }





    share|improve this answer


























      0














       getUser(): Observable<User> {
      const token = localStorage.getItem('access_token');
      return this.http.get<User>(
      'https://megaphone-test.herokuapp.com/api/user',
      {
      headers: new HttpHeaders().append('x-access-token', token)
      }
      );
      }





      share|improve this answer
























        0












        0








        0






         getUser(): Observable<User> {
        const token = localStorage.getItem('access_token');
        return this.http.get<User>(
        'https://megaphone-test.herokuapp.com/api/user',
        {
        headers: new HttpHeaders().append('x-access-token', token)
        }
        );
        }





        share|improve this answer












         getUser(): Observable<User> {
        const token = localStorage.getItem('access_token');
        return this.http.get<User>(
        'https://megaphone-test.herokuapp.com/api/user',
        {
        headers: new HttpHeaders().append('x-access-token', token)
        }
        );
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 15:25









        Clayton Allen

        808




        808















            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python