(Angular 6) Angular 通用 - 不等待内容 API 调用
(Angular 6) Angular Universal - Not waiting on content API call
在对使用动态内容的页面使用 Angular 通用时,无法使 SSR 工作。所有其他页面均有效,动态页面 return 具有 HTML,但不包含动态数据。
调用的方法:
ngOnInit() {
const div = this.renderer.createElement('div');
const texttest = this.renderer.createText('this works');
this.renderer.appendChild(div, texttest);
this.renderer.appendChild(this.content.nativeElement, div);
this.createLinkForCanonicalURL();
// The HTML never shows, the method works fine.
this._contentfulService.getBlogPosts().then(posts => {
this.blogPosts = _.orderBy(posts, ['sys.createdAt'], ['desc']);
});
}
服务方式
getBlogPosts(query ? : object): Promise<Entry<any>[]> {
return this.cdaClient.getEntries(Object.assign({
content_type: CONFIG.contentTypeIds.blogPosts
}, {
'fields.private': false
}))
.then(res => res.items);
}
模板:
这从未在源代码中显示。
<li class="blog-post" *ngFor="let post of blogPosts">
<h1>{{post.fields.title}}</h1>
</li>
已尝试入门工具包,但它们无法调用相同的方法。还尝试了 render2 注入和解析器服务来测试加载前获取数据。
似乎没有任何效果?
如有任何帮助,我们将不胜感激!
编辑
这是我的 server.ts 文件
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 8080;
const DIST_FOLDER = join(process.cwd(), 'dist');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } =
require('./dist/server/main');
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
和我的 应用程序服务器模块
@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule.withServerTransition({ appId: 'app-root' }),
AppModule,
ModuleMapLoaderModule,
ServerModule,
NoopAnimationsModule,
ServerTransferStateModule, // comment
]
})
export class AppServerModule { }
尝试按如下方式编辑您的代码:
async ngOnInit() {
const div = this.renderer.createElement('div');
const texttest = this.renderer.createText('this works');
this.renderer.appendChild(div, texttest);
this.renderer.appendChild(this.content.nativeElement, div);
this.createLinkForCanonicalURL();
const posts = await this._contentfulService.getBlogPosts();
this.blogPosts = _.orderBy(posts, ['sys.createdAt'], ['desc'])
}
angular universal 似乎不等待异步调用来呈现。
我遇到了同样的问题,最终使用 issue.
中提到的 ZoneMacroTaskWrapper 使其工作
这是我做的service
您需要使用 TransferHttpCacheModule for wait HTTP call to API or use another implementation that work with TransferState like ngx-transfer-http .
我的等待 3 秒延迟的示例:https://github.com/Angular-RU/angular-universal-starter/blob/master/src/app/transfer-back/transfer-back.component.ts
在对使用动态内容的页面使用 Angular 通用时,无法使 SSR 工作。所有其他页面均有效,动态页面 return 具有 HTML,但不包含动态数据。
调用的方法:
ngOnInit() {
const div = this.renderer.createElement('div');
const texttest = this.renderer.createText('this works');
this.renderer.appendChild(div, texttest);
this.renderer.appendChild(this.content.nativeElement, div);
this.createLinkForCanonicalURL();
// The HTML never shows, the method works fine.
this._contentfulService.getBlogPosts().then(posts => {
this.blogPosts = _.orderBy(posts, ['sys.createdAt'], ['desc']);
});
}
服务方式
getBlogPosts(query ? : object): Promise<Entry<any>[]> {
return this.cdaClient.getEntries(Object.assign({
content_type: CONFIG.contentTypeIds.blogPosts
}, {
'fields.private': false
}))
.then(res => res.items);
}
模板:
这从未在源代码中显示。
<li class="blog-post" *ngFor="let post of blogPosts">
<h1>{{post.fields.title}}</h1>
</li>
已尝试入门工具包,但它们无法调用相同的方法。还尝试了 render2 注入和解析器服务来测试加载前获取数据。
似乎没有任何效果?
如有任何帮助,我们将不胜感激!
编辑
这是我的 server.ts 文件
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 8080;
const DIST_FOLDER = join(process.cwd(), 'dist');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } =
require('./dist/server/main');
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
和我的 应用程序服务器模块
@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule.withServerTransition({ appId: 'app-root' }),
AppModule,
ModuleMapLoaderModule,
ServerModule,
NoopAnimationsModule,
ServerTransferStateModule, // comment
]
})
export class AppServerModule { }
尝试按如下方式编辑您的代码:
async ngOnInit() {
const div = this.renderer.createElement('div');
const texttest = this.renderer.createText('this works');
this.renderer.appendChild(div, texttest);
this.renderer.appendChild(this.content.nativeElement, div);
this.createLinkForCanonicalURL();
const posts = await this._contentfulService.getBlogPosts();
this.blogPosts = _.orderBy(posts, ['sys.createdAt'], ['desc'])
}
angular universal 似乎不等待异步调用来呈现。
我遇到了同样的问题,最终使用 issue.
中提到的 ZoneMacroTaskWrapper 使其工作这是我做的service
您需要使用 TransferHttpCacheModule for wait HTTP call to API or use another implementation that work with TransferState like ngx-transfer-http .
我的等待 3 秒延迟的示例:https://github.com/Angular-RU/angular-universal-starter/blob/master/src/app/transfer-back/transfer-back.component.ts