我想出了一個滿足我當時需求的解決方案。我用WebPack使用angular-cli,並且這可以滿足我的需求。我不明白我見過的所有使用「templateUrl:'/ Template/Index'」的例子,其中路徑是MVC視圖的路徑。這根本行不通,因爲無法在WebPack創建的任何捆綁視圖內找到路徑。也許這些人不使用angular-cli和WebPack。
這個計算器的回答 - How can I use/create dynamic template to compile dynamic Component with Angular 2.0?在創建下面的指令時非常有幫助。該指令將採用mvc局部視圖的輸出並對其進行編譯。它允許Razor /服務器邏輯發生,並且還可以編譯一些角度。儘管實際上在此MVC部分中包含其他組件是有問題的。如果你得到這個工作,請讓我知道你做了什麼。在我的情況下,我只需要服務器渲染髮生,並將其放置在我想要的Angular 2 spa中。
MvcPartialDirective
import {
Component,
Directive,
NgModule,
Input,
ViewContainerRef,
Compiler,
ComponentFactory,
ModuleWithComponentFactories,
ComponentRef,
ReflectiveInjector, OnInit, OnDestroy
} from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import {Http} from "@angular/http";
import 'rxjs/add/operator/map';
export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);
@NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }
return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
});
}
@Directive({ selector: 'mvc-partial' })
export class MvcPartialDirective implements OnInit, OnDestroy {
html: string = '<p></p>';
@Input() url: string;
cmpRef: ComponentRef<any>;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler, private http: Http) { }
ngOnInit() {
this.http.get(this.url)
.map(res => res.text())
.subscribe(
(html) => {
this.html = html;
if (!html) return;
if(this.cmpRef) {
this.cmpRef.destroy();
}
const compMetadata = new Component({
selector: 'dynamic-html',
template: this.html,
});
createComponentFactory(this.compiler, compMetadata)
.then(factory => {
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
});
},
err => console.log(err),
() => console.log('MvcPartial complete')
);
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
在一些-component.html(假設你的MVC應用程序與共享您的溫泉域)
<mvc-partial [url]="'/stuffs/mvcstuff'"></mvc-partial>
MvcStuff.cshtml
@{
ViewBag.Title = "This is some MVC stuff!!!";
}
<div>
<h2>MVC Stuff:</h2>
<h4>@ViewBag.Title</h4>
<h2>Angular Stuff:</h2>
<h4>{{1 + 1}}</h4>
</div>
in StuffsController。CS
public PartialViewResult MvcStuff() => PartialView();
這是正確的答案。奇蹟般有效。我認爲有時在服務器上預先呈現Angular模板是有意義的,因此您可以輕鬆呈現UserName或在其中執行其他用戶特定的業務邏輯(權限等)。 –
這是實現它的唯一方法嗎? – k11k2
得到''未定義'不可分配給類型'ComponentFactory''錯誤 –
k11k2