I have a simple angular application with server side rendering. I described ngOnInit of my component, where I call http.get method. But if I set debug on my Rest end-point I saw that this method called twice. Besides at first call I get HttpRequest without credentials, second one - with credentials. Why? And on console through console.log I saw only one call. How can I achive to call this rest only once and with credentials?
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {HttpModule} from "@angular/http";
import {FormsModule} from "@angular/forms";
import {HttpClientModule} from "@angular/common/http";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({appId: 'angular-universal'}),
FormsModule,
HttpClientModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.server.module.ts
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
ServerModule,
AppModule
],
bootstrap: [AppComponent]
})
export class AppServerModule { }
server.ts
import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
const PORT = 4000;
enableProdMode();
const app = express();
let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();
app.engine('html', (_, options, callback) => {
const opts = { document: template, url: options.req.url };
renderModuleFactory(AppServerModuleNgFactory, opts)
.then(html => callback(null, html));
});
app.set('view engine', 'html');
app.set('views', 'src')
app.get('*.*', express.static(join(__dirname, '..', 'dist')));
app.get('*', (req, res) => {
res.render('index', { req, preboot: true});
});
app.listen(PORT, () => {
console.log(`listening on http://localhost:${PORT}!`);
});
app.coponent.ts
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import {Hero} from "./hero";
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
title = 'app';
hero: Hero;
constructor(private http: HttpClient){
}
ngOnInit(): void {
this.http.get('http://localhost:8080/test', { withCredentials: true }).subscribe(data => {
console.log("Init component");
console.log(data);
});
}
}