Angular2 Universal如何处理ajax调用?

Mil*_*lad 8 typescript angular2-universal angular

我从他们发布它的那天起就一直在使用Angula2 + Universal,但今天我对它的实际工作方式感到困惑.

在他们的示例中,在server.ts文件中,您将找到:

app.get( '/data.json' , ( req , res ) => {
    res.json( {
        data : 'This fake data came from the server.'
    } );
} );
Run Code Online (Sandbox Code Playgroud)

如果您运行该应用程序,右键单击并查看页面源代码,您将在源代码中找到"此伪造数据来自服务器",这意味着该页面已在服务器中呈现?( 它是否正确 ? )

到目前为止,太棒了.

接下来是app.ts,你可以找到:

ngOnInit () {
        setTimeout( () => {
            this.server = 'This was rendered from the server!';
        } , 10 );
}
Run Code Online (Sandbox Code Playgroud)

同样,该文本也可以在页面源中找到.

现在这里是我的奇怪部分:

如果您出于任何原因增加服务器延迟,如:

app.get( '/data.json' , ( req , res ) => {
    setTimeout( function() {
        res.json( {
            data : 'This fake data came from the server.'
        } );
    } , 2000 ); // Added setTimeOut with 2 seconds .
} );
Run Code Online (Sandbox Code Playgroud)

这样,页面源不会获取文本,但是,如果您这样做:

app.get( '/data.json' , ( req , res ) => {
    setTimeout( function() {
        res.json( {
            data : 'This fake data came from the server.'
        } );
    } , 2 ); // **Added setTimeOut with 2 milli seconds.**
} );
Run Code Online (Sandbox Code Playgroud)

这一个,你可以在服务器中找到文本.!!!!!!

到目前为止,基于我的测试,我猜测ajax调用延迟是否很长(我猜是多于一秒?),你将无法从服务器端渲染中受益.

但是:

但是,如果您在app.component.ts中增加timeOut,例如:

ngOnInit () {
        setTimeout( () => {
            this.server = 'This was rendered from the server!';
        } , 3000 );  // Increased to 3 seconds
}
Run Code Online (Sandbox Code Playgroud)

您仍然可以获得服务器端渲染,源页面将呈现文本!

这里发生了什么事 ?

显然不是所有的ajax调用都可以低于1秒,那么使用通用的好处是什么呢?