404_Name_Not_Found
404_Name_Not_Found

Reputation: 437

How to let angular frontend wait for express REST-Call response

i want to make a REST-Call when i init my user Component so it will show the userprofile on load. This works fine, the component calls the service which calls my express backend which in turn makes a call to the REST-API which returns the userprofile. Then the Frontend gets updated.

However, i get a javascript error because the frontend tries to use the user.id before in the user components html template before the data is sent:

UserComponent.html:2 ERROR TypeError: Cannot read property 'id' of undefined
    at Object.eval [as updateRenderer] (UserComponent.html:2)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:20458)
    at checkAndUpdateView (core.js:19833)
    at callViewAction (core.js:20069)
    at execComponentViewsAction (core.js:20011)
    at checkAndUpdateView (core.js:19834)
    at callViewAction (core.js:20069)
    at execComponentViewsAction (core.js:20011)
    at checkAndUpdateView (core.js:19834)
    at callViewAction (core.js:20069)

i tried to get around this behaviour by adding default values that i want to be used while the user gets loaded Here is my HTML:

<ul>
  <li>id: {{user.id ? user.id : ''}}</li>
  <li>name: {{user.firstName ? user.firstName : ''}} {{user.lastName ? user.lastName : ''}}</li>
  <li>mail: {{user.email ? user.email : ''}}</li>
</ul>

Here is the component.ts

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

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUser().subscribe(user => {
      console.log('myUser: ' + JSON.stringify(user));
      this.user = user;
    });
  }

}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';

import { User } from '../classes/user';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) {  }

  getUser(): Observable<User> {
    return this.http.get<any>('/api/userprofile');
  }
}

and the serverside code

router.get('/userprofile', (req, res) => {
  axios.get('https://somerestapi', {auth: {username: 'authuser', password: 'authuserpw'}})
    .then(response => {
      res.status(200).json(response.data)
    })
    .catch(error => {
      res.status(500).send(error);
    })
})

Thanks in advance!

Upvotes: 0

Views: 562

Answers (4)

Ankur Jain
Ankur Jain

Reputation: 221

Try to use below html snippet:

<ul>
  <li>id: {{user?.id}}</li>
  <li>name: {{user?.firstName}} {{user?.lastName}}</li>
  <li>mail: {{user?.email}}</li>
</ul>

Or

  <ul *ngIf="user.length >0">
  <li>id: {{user.id ? user.id : ''}}</li>
  <li>name: {{user.firstName ? user.firstName : ''}} {{user.lastName ? user.lastName : ''}}</li>
  <li>mail: {{user.email ? user.email : ''}}</li>
</ul>

Upvotes: 1

arun kumar
arun kumar

Reputation: 1171

<ul *ngIf="user">
  <li>id: {{user.id ? user.id : ''}}</li>
  <li>name: {{user.firstName ? user.firstName : ''}} {{user.lastName ? user.lastName : ''}}</li>
  <li>mail: {{user.email ? user.email : ''}}</li>
</ul>

You can call a function inside the ngOnInit , like follows

 ngOnInit() {
    this.userService.getUser().subscribe(user => {
      console.log('myUser: ' + JSON.stringify(user));
      this.assignUser(this.user) ;
    });
  }
  //function to assinging user value
      assignUser(user){
      this.user= user;
      }

Upvotes: 1

brk
brk

Reputation: 50326

Try by checking the length of user array

<ul *ngIf="user.length >0">
  <li>id: {{user.id ? user.id : ''}}</li>
  <li>name: {{user.firstName ? user.firstName : ''}} {{user.lastName ? user.lastName : ''}}</li>
  <li>mail: {{user.email ? user.email : ''}}</li>
</ul>

Upvotes: 0

Carsten
Carsten

Reputation: 4208

Either put *ngIf="user" on the ul element. Or put the question mark after every user in the html. <li>id: {{user?.id}}</li>

Upvotes: 3

Related Questions