json - 如何使用 Angular Universal 在服务器端渲染中加载 json

标签 json node.js angular server-side-rendering angular-universal

我正在为我的学士论文的大学项目构建一个 angular2 通用应用程序。我想用 Angular Universal 在服务器上渲染这个应用程序。如何将 .json 文件加载到服务器上?在我的没有服务器端渲染的版本中,我使用服务通过 http.get 请求获取 json,如下所示:

@Injectable()
export class VideoService {

private movieSubject: BehaviorSubject<Video[]> = new BehaviorSubject<Video[]>([]);
  movies$: Observable<Video[]> = this.movieSubject.asObservable();

constructor(private http : Http) {
    this.http.get('./json/movies/movies.json').subscribe(
      res => this.movieSubject.next(res.json()),
      error => console.error(error)
    )
}
}

在我的组件中,我使用以下代码获取 json:

movieInfos: MovieInfos;

  constructor(private movieService: MovieService) {
    movieService.movies$.subscribe(
      infos => this.movieInfos = infos,
      error => console.error(error)
    );
  }

在模板中,我使用下面的代码将数据注入(inject)到另一个组件:

<app-info-site *ngIf="movieInfos" [movieInfos]="movieInfos"></app-info-site>

当我将这段代码与 Angular Universal 一起使用时,它仍然有效,但是属于 json 的站点部分是第一次在客户端上加载的,并且由于 ngIf 服务器忽略了这部分代码,所以我从服务器获取不完整的 .html 文件。我怎样才能将其加载到服务器上以从那里获取完整的 .html 站点?

PS:我对 Angular2 和服务器端渲染完全陌生。

最佳答案

首先,我建议您迁移到 Angular4,因为服务器端渲染现在是 Angular4 的一部分,并且不需要 Angular Universal...

您还可以查看http://rajdeepdeb.me/angular-server-side-rendering-with-a-simple-node-server/

要在现有结构中回答,您应该通过实现 OnInit 将 http 调用从构造函数移动到 ngOnInit

import { OnInit } from '@angular/core';

export class YourComponent implements OnInit {
    ...other variable and functions...
    ngOnInit() {
        this.http.get('./json/movies/movies.json').subscribe(
            res => this.movieSubject.next(res.json()),
            error => console.error(error)
        );
    }
}

如果您需要任何其他支持,请告诉我...

关于json - 如何使用 Angular Universal 在服务器端渲染中加载 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297000/

相关文章:

json - 编码 time.Time 到 unix 时间戳

javascript - 解析带引号的简单 json 时出现语法错误?

javascript - JSON.parse 出现问题,不知道为什么没有解析所有内容

javascript - 删除数据后更新对象的对象

python - 如何将 JSON 时间序列与具有相同列名的 pandas 一起使用

javascript - 无法通过nodejs中的nodemailer发送电子邮件

javascript - 在循环内使用 setTimeout 不允许阻塞

json - 有没有办法在 Angular 项目的 asset 文件夹中编辑 JSON 文件?

angular - 如何在 Angular Jasmine 规范中模拟路由器

angular - 为什么添加 HTTP 拦截器会导致 CORS 错误?