Search code examples
node.jsangulartypescriptasynchronousangular-resolver

Angular6 Synchronously Load Route Data


Okay, I recently implemented SSR into my Angular6 application, with the intention of rendering dynamic HTML in a crawlable manner. All seems to be working fine, but my issue is rendering data from an API endpoint.

As soon as a user arrives on my site, a list of top posts that have been retrieved from a Node server will be displayed. In order to retrieve the data before page load, I implemented a resolver for my posts service. The resolver will resolve an Observable, which will then be accessed by my component.

resolver.service.ts :

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { PostService } from '../services/post.service';
import { of } from 'rxjs';


@Injectable()
export class ResolverService implements Resolve<any> {
  constructor(private postService: PostService) { }

  resolve (){
    return of(this.postService.getPosts());
  }
}

This Observable will be correctly resolved and can be accessed in my component like so,

content.component.ts :

  ...
  posts: any;

  constructor(private route:ActivatedRoute){}

  ngOnInit() {
    this.route.snapshot.data['posts'].subscribe(
      data =>{
        this.posts = JSON.parse(JSON.stringify(data));
      }
    );
  }
  ...

Then the posts variable will be rendered in the html. The problem is, when using a subscription, my data is not rendered in the source because subscriptions work asynchronously. I need the data to be extracted before page load.

If anyone can point me in the correct direction, it would be much appreciated. Thanks.


Solution

  • Found the solution. I was previously using the HttpClient module to handle api calls, it turns out that I needed to use the Http module with the following approach I discovered thanks to @IftekharDani 's example.

    resolver.service.ts:

    import { Http } from '@angular/http';
    
    ...
    
    getPosts(): Observable<any> {
        return this.http.get("<your site>/api/posts/all", { })
        .pipe(
          map(
          res => {
            return res.json();
          },
          err => {
            return err;
          }
          )
        );
      }
    
      resolve (route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
        return this.getPosts();
      }
    

    content.component.ts:

    ...
    ngOnInit() {
        this.posts = this.route.snapshot.data['posts'];
    }
    ...
    

    app-routing.module.ts

    import { ResolverService } from './services/resolver.service';
    
    const routes: Routes = [
      ...
      { path: '**', component: ContentComponent, resolve: { posts: ResolverService}}
    ];