Angular6 Synchronously Load Route Data

有些话、适合烂在心里 提交于 2019-12-11 04:37:17

问题


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.


回答1:


Add ngIf Condition in HTML may solve your problem.

Example :

<ul *ngIf="posts">
  <li>Title : {{posts.title}}</li>
</ul>

Refrence Link : here

check the file contacts-detail.component.ts in a provided demo for more understanding.




回答2:


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}}
];


来源:https://stackoverflow.com/questions/53580756/angular6-synchronously-load-route-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!