typescript - 由于 NgZone 引用错误,预渲染失败

标签 typescript visual-studio-code angular2-services asp.net-core-2.0 angular2-zone

我在实现 NgZones 时遇到了问题。即使我已经定义了 NgZone,我也会收到这个错误。 “NodeInvocationException:由于错误而导致预呈现失败:ReferenceError:未定义 NgZone”

这是我的 app.error-handle.ts 文件,我在其中使用了 NgZone。

   import { ToastyService } from 'ng2-toasty';
import { ErrorHandler, Inject, NgZone } from '@angular/core';

export class AppErrorHandler implements ErrorHandler {
  constructor(
    private ngZone: NgZone,
    @Inject(ToastyService) private toastyService: ToastyService) {
  }

  handleError(error: any): void {
    this.ngZone.run(() => {
      this.toastyService.error({
        title: 'Error',
        msg: 'An unexpected error happened.',
        theme: 'bootstrap',
        showClose: true,
        timeout: 5000
      });
    });

  }
}

这是我的 webpack.config.vendor.js 文件。

const path = require('path');
    const webpack = require('webpack');
    const ExtractTextPlugin = require('extract-text-webpack-plugin');
    const merge = require('webpack-merge');
    const treeShakableModules = [
        '@angular/animations',
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/forms',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        'zone.js',
    ];
    const nonTreeShakableModules = [
        'bootstrap',
        'bootstrap/dist/css/bootstrap.css',
        'es6-promise',
        'es6-shim',
        'event-source-polyfill',
        'ng2-toasty',
        'ng2-toasty/bundles/style-bootstrap.css',
        'jquery'
    ];
    const allModules = treeShakableModules.concat(nonTreeShakableModules);

    module.exports = (env) => {
        const extractCSS = new ExtractTextPlugin('vendor.css');
        const isDevBuild = !(env && env.prod);
        const sharedConfig = {
            stats: { modules: false },
            resolve: { extensions: [ '.js' ] },
            module: {
                rules: [
                    { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
                ]
            },
            output: {
                publicPath: 'dist/',
                filename: '[name].js',
                library: '[name]_[hash]'
            },
            plugins: [
                new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
                new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
                new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
                new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
            ]
        };

        const clientBundleConfig = merge(sharedConfig, {
            entry: {
                // To keep development builds fast, include all vendor dependencies in the vendor bundle.
                // But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
                vendor: isDevBuild ? allModules : nonTreeShakableModules
            },
            output: { path: path.join(__dirname, 'wwwroot', 'dist') },
            module: {
                rules: [
                    { test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
                ]
            },
            plugins: [
                extractCSS,
                new webpack.DllPlugin({
                    path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                    name: '[name]_[hash]'
                })
            ].concat(isDevBuild ? [] : [
                new webpack.optimize.UglifyJsPlugin()
            ])
        });

        const serverBundleConfig = merge(sharedConfig, {
            target: 'node',
            resolve: { mainFields: ['main'] },
            entry: { vendor: allModules.concat(['aspnet-prerendering']) },
            output: {
                path: path.join(__dirname, 'ClientApp', 'dist'),
                libraryTarget: 'commonjs2',
            },
            module: {
                rules: [ { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] } ]
            },
            plugins: [
                new webpack.DllPlugin({
                    path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                    name: '[name]_[hash]'
                })
            ]
        });

        return [clientBundleConfig, serverBundleConfig];
    }

最佳答案

最近我遇到了同样的问题,我通过在 @Inject 装饰器的帮助下在构造函数中注入(inject) NgZone 解决了这个问题。

所以,尝试替换

private ngZone: NgZone

@Inject(NgZone) private ngZone: NgZone

希望对你有帮助。

关于typescript - 由于 NgZone 引用错误,预渲染失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46536430/

相关文章:

vim - 引用 NativeScript UI 插件的核心模块

javascript - 使用 lodash 的 typescript 字符串插值

angular - 如何在 Angular 7 中使用 typescript 获取属性值

java - 扩展主机意外终止 (vscode)

angular - 当 Observable/订阅更改属性时 ngOnChanges 不触发

node.js - 解析器中的 Angular HttpClient 问题

javascript - JavaScript Intellisense VScode 问题 [ts()]

java - 如何修复 "{"名称“:"error","attributes": {"message" :"Exception happens in the Test Runner." in VS code

angularjs-directive - typescript 错误 TS2339 : Property 'project' does not exist on type '{}'

treeview - 从数据 API 动态创建递归 TreeView 的最佳方法