Colin Ragnarök
Colin Ragnarök

Reputation: 1062

Cannot read property 'username' of null, when trying to access id-data

I want to pass a users data on to its profile. I get the full data from the api and I can fetch and display it on the users page. But when I want to display the data from the user on the users profile page I get this error:

TypeError: Cannot read property 'username' of null

The routing works. But somehow I don't have access to the users info which I want to store in information. And I think this line should store the data of the user:

this.userService.getUserDetails(id).subscribe(result => {
       this.information = result;
     });

How can I fix that? Here is my code:

user.service

 // get a list of users
  getList(): Observable<any> {
    return this.http.get(`${this.url}/users`);
  }

 // get a user's profile
  getUserDetails(id): Observable<any> {
    return this.http.get(`${this.url}/users/?i=${id}`); // why add ?i
  }

user.page.ts

 getAllFriends() {
    this.friendsList = this.userService.getList()
    .pipe(map(response => response.results));
  }

profile.page.ts

information = null;
    ...
ngOnInit() {

         // Get the ID that was passed with the URL
         let id = this.activatedRoute.snapshot.paramMap.get('id');

         // Get the information from the API
         this.userService.getUserDetails(id).subscribe(result => {
           this.information = result;
         });
       }

profile.page.html

<ion-label text-wrap>
      <h6 class="subinfo">{{information.username}},&nbsp;22,&nbsp;3589</h6>
</ion-label>

Upvotes: 1

Views: 685

Answers (1)

Wandrille
Wandrille

Reputation: 6811

your component start with information = null; so it's normal that in {{ information.username }} you have this error.

A quick solution is:

{{ information?.username }}

Upvotes: 2

Related Questions