繁体   English   中英

发生错误:无法读取 null 的属性“nativeElement”

[英]An error occurred: Cannot read property 'nativeElement' of null

我正在尝试修改现有的 ASP.NET Core Angular 8 应用程序以在生产模式下构建和运行,以便使用 serviceWorkers。 所以我遵循了这篇文章中的建议 我也在根据这篇文章生成源映射。

我修改了我的项目以通过修改项目文件并添加以下内容来运行“npm run build -- --prod --source-map”:

<Target Name="BuildAngular" BeforeTargets="Build">
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build -- --prod --source-map" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --prod --source-map" Condition="'$(BuildServerSideRenderer)'=='true'" />
  </Target>

我还修改了 startup.cs 代码以不再使用

spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");

所以现在我有:

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501
            // -
            spa.Options.SourcePath = "ClientApp";

        });

我还修改了调试配置以启动程序而不是启动 IIS。 我还在启动浏览器。 我不再在 clientApp 目录的 powershell 窗口中运行“npm start”。

一切似乎都很好,程序启动并显示:

Hosting environment: Dev
Content root path: C:\Users\olivier.matrot\source\repos\SafeProtect\WebAdministration\SafeProtect.WebAdmin.Web
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

浏览器启动并尝试打开 localhost:5001。 然后它立即弹出:

发生错误:无法读取空 URL 的属性“nativeElement”:/

这里发生了什么?

编辑:这是配置代码:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            try
            {
                this.logger.Format(SeverityLevel.Info, "[Configure]");

                // else if (env.IsProduction() || env.IsStaging() || env.IsEnvironment("Dev") || env.IsEnvironment("Test"))
                if (env.IsDevelopment())
                {
                    app.UseDatabaseErrorPage();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");

                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseSpaStaticFiles();

                // application.UseFileServer();
                app.UseSession();
                app.UseJwtBearerTokens(
                    app.ApplicationServices.GetRequiredService<IOptions<TokenProviderOptions>>(),
                    PrincipalResolver);

                // -------------------------------------------------------------
                IList<CultureInfo> supportedCultures = new List<CultureInfo>()
                {
                    new CultureInfo("fr-FR"),
                    new CultureInfo("en-US"),
                };

                app.UseRequestLocalization(new RequestLocalizationOptions
                {
                    DefaultRequestCulture = new RequestCulture("fr-FR"),

                    // Formatting numbers, dates, etc.
                    SupportedCultures = supportedCultures,

                    // UI strings that we have localized.
                    SupportedUICultures = supportedCultures,
                });

                // -------------------------------------------------------------
                // app.UseMvc(routes =>
                // {
                //    routes.MapRoute(
                //        name: "default",
                //        template: "{controller}/{action=Index}/{id?}");
                // });
                app.UseMvc(routes =>
                {
                    routes.MapRouteAnalyzer("/routes");
                    routes.MapRoute("default", "api/{controller}/{action}/{id?}");
                });

                // To get the IP Address of the client in controllers
                // https://stackoverflow.com/a/41335701/15186
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                    ForwardedHeaders.XForwardedProto,
                });

                app.UseAuthentication();

                // -------------------------------------------------------------
                app.UseCors(x => x
                    .SetIsOriginAllowed((host) => true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());

                app.UseRouting();

                // -------------------------------------------------------------
                // Create a real-time comunication application
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapHub<ServerHub>("/serverhub");
                });

                // Warning, the use of SignalR must be set before UseSpa otherwise you'll get a negotiation error (404) when connecting to the hub.
                app.UseSpa(spa =>
                {
                    // To learn more about options for serving an Angular SPA from ASP.NET Core,
                    // see https://go.microsoft.com/fwlink/?linkid=864501
                    // -
                    spa.Options.SourcePath = "ClientApp";

                    if (env.IsDevelopment())
                    {
                        // spa.UseAngularCliServer(npmScript: "start");
                        // spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                    }
                });

                // -------------------------------------------------------------
                // Handle errors
                app.UseExceptionHandler(appError =>
                {
                    appError.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = MediaTypeNames.Application.Json;

                        var exception = context.Features.Get<IExceptionHandlerFeature>();

                        if (exception != null)
                        {
                            SafeProtectLogHelper.Instance.WebApiLogger.WriteException(exception.Error, SeverityLevel.Error);
                            await context.Response
                                .WriteAsync(JsonConvert.SerializeObject(exception.Error?.Message))
                                .ConfigureAwait(continueOnCapturedContext: false);
                        }
                    });
                });

                // Allow the controllers to read the browser supported cultures
                app.UseRequestLocalization();

                // applicationLifetime.ApplicationStarted.Register(() =>
                // {
                //     var infos = routeAnalyzer.GetAllRouteInformations();
                //     var category = @"RouteAnalyzer";
                //     this.logger.Write(category, SeverityLevel.Debug, "======== BEGIN DUMP ALL ROUTE INFORMATION ========");
                //     foreach (var info in infos)
                //     {
                //         this.logger.Write(category, SeverityLevel.Debug, info.ToString());
                //     }
                //     this.logger.Write(category, SeverityLevel.Debug, "======== END DUMP ALL ROUTE INFORMATION ========");
                // });
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                this.logger.Format(this.logger.DefaultCategory, this.logger.DefaultTrackInfo, ex.ToString(), SeverityLevel.Error, "Configure => Unexpected exception : {0}", ex.Message);
            }
        }

这个问题与我使用的 MDB Angular Pro 版本有关。 最初它是来自主分支的 8.2.0。

因为我的 package.json 文件在大约一年前注册了隐式 master 分支,现在它们是 8.8.1,这是在 node_modules 刷新后出现的这个版本。

通过引用所需的版本来解决问题(注意#8.2.0 ):

"ng-uikit-pro-standard": "git+ https://git.mdbootstrap.com/mdb/angular/ng-uikit-pro-standard.git#8.2.0 "

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM