Angular5 Server side rendering, external Api data service does not work in ssr

Discussão em 'Angular' iniciado por Jihoon Kwon, Dezembro 23, 2024.

  1. Jihoon Kwon

    Jihoon Kwon Guest

    I have set up and used successfully Angular5 + SSR. It is still pretty nice.

    All components work well on SSR and Non-SSR. And there are some services which call external HTTP get APIs to get some data. Of course, it works well on a Non-SSR mode.

    But, the problem is that on SSR, the node server does not 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 calls HTTP request data and render it on index.html but it's not...

    Am I missing or misunderstood?

    ps : The same issues are reported. https://github.com/angular/universal/issues/674 If I solve these issues or find out the good doc, I would update it again. :)

    Continue reading...

Compartilhe esta Página