[英]How to realize website with hundreds of pages in Angular2
我正在准備SPA網站,其中包含數百個類似文章的頁面(除了電子商務,登錄等)。 每篇文章都有自己的URL。 我想用Angular2來實現它。 到目前為止我找到的唯一解決方案是:
1.准備數百個Agular2組件,每篇文章一個組件......
...使用指向文章標記的templateUrl。 所以我需要數百種類似的組件:
@core.Component({
selector: 'article-1',
templateUrl: 'article1.html'
})
export class Article1 {}
2.使用AsyncRoute
顯示文章
@core.Component({
selector: 'article-wrapper',
template: '<router-outlet></router-outlet>'
})
@router.RouteConfig([
new router.AsyncRoute({
path: '/article/:id',
loader: () => {
switch (id) {
case 1: return Article1;
case 2: return Article2;
//... repeat it hundreds of times
}
},
name: 'article'
})
])
class ArticleWrapper { }
在Angular1中有ngInclude指令,由於安全問題,Angular2中缺少該指令(參見此處 )。
[編輯1]代碼本身不僅存在問題。 問題還在於此解決方案的靜態性質 。 如果我需要帶有站點地圖和動態頁面結構的網站 - 添加單個頁面需要重新編譯整個ES6 JavaScript模塊。
[編輯2]概念“標記x html作為數據”(標記不僅是靜態HTML而且是帶有活動組件的HTML)是整個Web的基本概念(每個CMS在數據庫中都有其標記數據)。 如果沒有Angular2解決方案,它就會否認這個基本概念。 我相信必須有一些技巧。
以下所有解決方案都很棘手。 官方Angular團隊支持問題就在這里 。
感謝@EricMartinez指點我@alexpods解決方案 :
this.laoder.loadIntoLocation(
toComponent(template, directives),
this.elementRef,
'container'
);
function toComponent(template, directives = []) {
@Component({ selector: 'fake-component' })
@View({ template, directives })
class FakeComponent {}
return FakeComponent;
}
和另一個類似的( 來自@jpleclerc ):
@RouteConfig([
new AsyncRoute({
path: '/article/:id',
component: ArticleComponent,
name: 'article'
})
])
...
@Component({ selector: 'base-article', template: '<div id="here"></div>', ... })
class ArticleComponent {
public constructor(private params: RouteParams, private loader: DynamicComponentLoader, private injector: Injector){
}
ngOnInit() {
var id = this.params.get('id');
@Component({ selector: 'article-' + id, templateUrl: 'article-' + id + '.html' })
class ArticleFakeComponent{}
this.loader.loadAsRoot(
ArticleFakeComponent,
'#here'
injector
);
}
}
有點不同( 來自@ peter-svintsitskyi ):
// Faking class declaration by creating new instance each time I need.
var component = new (<Type>Function)();
var annotations = [
new Component({
selector: "foo"
}),
new View({
template: text,
directives: [WordDirective]
})
];
// I know this will not work everywhere
Reflect.defineMetadata("annotations", annotations, component);
// compile the component
this.compiler.compileInHost(<Type>component).then((protoViewRef: ProtoViewRef) => {
this.viewContainer.createHostView(protoViewRef);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.