0

I simply want to retrieve data before the page is loaded in order to be able to display this data.

user.service.ts

export class UserService {

  constructor(private httpClient: HttpClient) { }

  getUserDetails(username) {
    return this.httpClient.get<User[]>(`http://localhost:8080/users/` + username)
    .pipe(
      map(
        userData => {
          console.log(userData);
          return userData;
        }
      )
    );
  }
}

account.component.ts

export class AccountComponent implements OnInit {

  username: string;

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }

  constructor(private authenticationService: AuthenticationService, private userService: UserService, private router: Router) {
    this.username = sessionStorage.getItem('username');
    this.userService.getUserDetails(this.username);
  }

  logout() {
    this.authenticationService.logOut();
  }
}
Tom van den Bogaart
  • 143
  • 1
  • 4
  • 15

2 Answers2

2

If I were you, in order to get async data in my template I would simply do :

<div *ngIf="myData !== null">
…
</div>

This simple trick allows you to display async data without having errors.

Eudz
  • 540
  • 6
  • 19
2

You need to use a resolver in order to do that. A resolver is a class that implements resolve<resolveType> and uses one method resolve. In the resolve function, you can use injected service to returns an observable with your data :

@Injectable({ providedIn: 'root' })
export class userResolver implements Resolve<anu> {
  constructor(private userService: UserService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any>| {
    return this.userService.getUserById(route.paramMap.get('id'));
  }
}

In this example, we inject the userService and use a method to returns an Observable. Please note that i'm using any to simplify here. In this case, the route parameters contains the current route we are trying to resolve. Let's say /user/1. We can use this object to retreive information about the current route, like the user Id.

Our resolver can then be used in the route of a particular page. It will be run before the onInit function of the page. To add it to a page, you need to call the function in the resolve portion of its route :

let route =  [
      {
        path: 'user/:id',
        component: UserComponent,
        resolve: {
          hero /* the name we will use in the onInit to get the data */: Resolver /* our resolver */
        }
      }
    ])
...

We can then access the resolved data in the onInit function :

export class UserComponent {
...
    constructor(private route: ActivatedRoute) {}

    ngOnInit(){
         this.route.subscribe(data => {
             // we do something with our data.
         });
    }
}

You can get more information at the official Angular docs;

Nicolas
  • 8,077
  • 4
  • 21
  • 51