尝试设置平台服务器时出现“错误:在此配置中,Angular需要Zone.js”

时间:2018-08-27 20:12:51

标签: angular

仍然尝试设置平台服务器并使用自定义渲染器(我尚未实现)渲染模块。

问题

  • 我遇到了一个我不知道如何解决的错误(zone.js在我的npm依赖项中)。
      

    错误:在这种配置下,Angular需要Zone.js

  • 我什至不确定我是否会朝着自定义模块渲染的方向前进...

主要代码

export function createCompiler(compilerFactory: CompilerFactory) {
  return compilerFactory.createCompiler();
}

async function generate<M>(moduleType: Type<M>) {
  try {
    const extraProviders: StaticProvider[] = [
      { provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory] },
    ];
    const platformRef = platformDynamicServer(extraProviders);
    const moduleRef = await platformRef
      .bootstrapModule(
        moduleType,
        {
          providers: [ { provide: ResourceLoader, useValue: new ResourceLoaderImpl(`src\\app`), deps: [ ] }, ],
        });

    const appComponent = moduleRef.injector.get(AppComponent);

    console.info(appComponent.title.toString());
  } catch (error) {
    throw new Error(error.toString());
  }
}

generate(AppModule)
  .then(message => console.info({ message }))
  .catch(error => console.error({ error }));

自定义资源加载器

@Injectable()
export class ResourceLoaderImpl extends ResourceLoader {
  constructor(private _cwd: string) {
    super();
  }

  get(resourceFileName: string): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      glob(`**/${resourceFileName}`, { cwd: this._cwd, }, (globError, matches) => {
        if (globError) reject(globError);
        else
          readFile(
            path.join(this._cwd, matches[0]),
            (readFileError, data) => {
              if (readFileError) reject(readFileError);
              else resolve(data.toString());
            }
          );
      });
    });
  }
}

进口

import { ResourceLoader } from '@angular/compiler';
import { Compiler, CompilerFactory, Injectable, StaticProvider, Type } from '@angular/core';
import { platformDynamicServer } from '@angular/platform-server';
import { readFile } from 'fs';
import * as glob from 'glob';
import * as path from 'path';
import { AppComponent } from './app/app.component';
import { AppModule } from './app/app.module';

1 个答案:

答案 0 :(得分:1)

修复了静态导入 subscriptionCat: Subscription; filterdProduct: any[]; products: any[] = []; categories: any[]; category: string; ngOnInit() { this.productService.getAll().pipe(switchMap(prodData => { this.products = prodData; console.log(this.products); return this.route.queryParamMap })).subscribe(params => { this.category = params.get('category'); this.filterdProduct = (this.category) ? this.products.filter(p => { p.category === this.category }) : this.products; }); this.subscriptionCat = this.categoryService.getCategories() .subscribe(catData => { this.categories = catData; }); }

zone.js