I have setup and used successfully Angular5 + SSR. It is still pretty nice.
All components works well on SSR and Non-SSR. And there are some services which calls external HTTP get apis to get some data. Of course it work well on a Non-SSR mode.
But, the problem is that on SSR, node server does dot support to fetch and render the data. I can only see the fetched data after client side fetching and rendering.
import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs";
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class BannerService {
constructor(public http: HttpClient){
console.log('SmsService Initialized...');
}
getBanners(){
return this.http.get(BASE_API_URL + '/getData', httpOptions);
}
}
home.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import { Router } from "@angular/router";
import {Subscription} from "rxjs/Subscription";
import {BannerService} from "../../services/banner.service";
@Component({
selector: 'app-home',
styleUrls: ['home.container.css'],
templateUrl: 'home.container.html'
})
export class HomeContainerComponent implements OnInit, OnDestroy {
public horizontalBannerList1;
public horizontalBannerList2;
public verticalBannerList;
private bannerList;
constructor( private router: Router, private bannerService: BannerService){
...
}
ngOnInit() {
this.initBannerList();
}
ngOnDestroy() {
...
}
initBannerList(){
if(this.bannerList){
return;
}
this.bannerService.getBanners().subscribe(
result => {
console.log("bannerList result : ", result);
this.bannerList = result;
},
error => {
console.error("bannerList error: ", error);
},
() => {
console.log("bannerList completed");
});
}
}
I expected that on SSR the node server call http request data and render it on index.html but it's not....
Am I missing or misunderstood?
ps : Same issues are reported. https://github.com/angular/universal/issues/674 If I solve this issues or find out good doc, I would update it again. :)
This article explains how to do backend calls within angular universal. https://angular.io/guide/universal#absolute-http-urls
来源:https://stackoverflow.com/questions/49355650/angular5-server-side-rendering-external-api-data-service-does-not-work-in-ssr