Angular6 同步加载路由数据

Angular6 Synchronously Load Route Data

好的,我最近在我的 Angular6 应用程序中实现了 SSR,目的是以可抓取的方式呈现动态 HTML。一切似乎都工作正常,但我的问题是从 API 端点呈现数据。

一旦用户到达我的网站,就会显示从节点服务器检索到的热门帖子列表。为了在页面加载之前检索数据,我为我的帖子服务实现了一个解析器。解析器将解析一个 Observable,然后我的组件将访问它。

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());
  }
}

这个 Observable 将被正确解析,并且可以像这样在我的组件中访问,

content.component.ts :

  ...
  posts: any;

  constructor(private route:ActivatedRoute){}

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

然后 posts 变量将在 html 中呈现。问题是,当使用订阅时,我的数据不会在源中呈现,因为订阅是异步工作的。我需要在页面加载之前提取数据。

如果有人能指出正确的方向,我将不胜感激。谢谢

Add ngIf Condition in HTML may solve your problem.

示例

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

参考 Link : here

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

找到解决方案。我以前使用 HttpClient 模块来处理 api 调用,事实证明我需要使用 Http 模块和我发现的以下方法感谢@IftekharDani 的示例。

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