【发布时间】:2018-03-21 13:10:33
【问题描述】:
我有一个带有服务器端渲染的简单 Angular 应用程序。我描述了我的组件的 ngOnInit,我在其中调用了 http.get 方法。但是如果我在我的 Rest 端点上设置调试,我会看到这个方法调用了两次。除了第一次调用我得到 HttpRequest 没有凭据,第二个 - 有凭据。为什么?在控制台上通过 console.log 我只看到一个电话。我怎样才能实现只调用一次并使用凭据?
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);
});
}
}
【问题讨论】: