Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 2.0路由器无法重新加载浏览器_Angular_Angular2 Routing - Fatal编程技术网

Angular 2.0路由器无法重新加载浏览器

Angular 2.0路由器无法重新加载浏览器,angular,angular2-routing,Angular,Angular2 Routing,我使用的是Angular 2.0.0-alpha.30版本。当重定向到其他路由,然后刷新浏览器时,其显示无法获取/路由 你能帮我弄清楚为什么会发生这个错误吗。我想你看到的错误是因为你的请求不存在。您需要确保服务器将所有请求映射到主index.html页面 由于Angular 2默认使用html5路由,而不是在url末尾使用哈希,因此刷新页面看起来像是请求其他资源。免责声明:此修复程序适用于Alpha44 我也遇到了同样的问题,通过实现Angular.io API预览中列出的HashLocatio

我使用的是Angular 2.0.0-alpha.30版本。当重定向到其他路由,然后刷新浏览器时,其显示无法获取/路由


你能帮我弄清楚为什么会发生这个错误吗。

我想你看到的错误是因为你的请求不存在。您需要确保服务器将所有请求映射到主index.html页面

由于Angular 2默认使用html5路由,而不是在url末尾使用哈希,因此刷新页面看起来像是请求其他资源。

免责声明:此修复程序适用于Alpha44

我也遇到了同样的问题,通过实现Angular.io API预览中列出的HashLocationStrategy解决了这个问题

从导入必要的指令开始

import {provide} from 'angular2/angular2';
import {
  ROUTER_PROVIDERS,
  LocationStrategy,
  HashLocationStrategy
} from 'angular2/router';
最后,像这样把它全部引导到一起

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
]);
您的路线将显示为,当您刷新时,它将在适当的位置重新加载

希望有帮助

您看到的错误是因为您正在请求http://localhost/route 这是不存在的。根据

使用html5路由时,您需要将应用程序(当前为404)中的所有路由映射到服务器端的index.html。以下是您的一些选择:

  • 使用live server:

  • 使用nginx:


  • Tomcat—web.xml的配置。根据他的评论

    <error-page>
          <error-code>404</error-code>
          <location>/index.html</location>
    </error-page>
    
    
    404
    /index.html
    

  • 确保将其放置在index.html的head元素中:

    <base href="/">
    
    
    
    Angular2文档中的代码在头部使用以下代码(它们在文档的实时示例注释中解释了原因):

    document.write(“”);
    

    刷新页面时,这将动态地将基本href设置为当前document.location。我可以看到,这给浏览文档和试图复制plunker的人带来了一些困惑。

    服务器配置不是SPA的解决方案,甚至我都这么认为。如果有错误的路线进入,你不想重新装填角形水疗,是吗?因此,我将不依赖于服务器路由并重定向到其他路由,但是的,我将让index.html处理angular应用程序路径的所有角度路由请求

    尝试此方法,而不是其他方法或错误的路线。它对我有效,不确定,但似乎正在进行中。我自己在面对一个问题时也遇到了这个问题

    @RouteConfig([
      { path: '/**', redirectTo: ['MycmpnameCmp'] }, 
       ...
      }
    ])
    


    但是,请记住,如果您的HTML或web脚本不是SPA,请配置您的服务器文件夹和访问权限。否则你将面临问题。对我来说,当我面对像你这样的问题时,它是服务器配置和以上配置的混合。

    Angular默认使用HTML5 pushstate(
    PathLocationStrategy
    在Angular俚语中)。
    您需要一个服务器来处理所有请求,就像它在请求
    index.html
    一样,或者切换到
    HashLocationStrategy
    (路由的URL中带有#)

    另见

    要切换到HashLocationStrategy,请使用

    更新>=RC.5和2.0.0最终版本

    从'@angular/common'导入{HashLocationStrategy,LocationStrategy};
    @NGD模块({
    声明:[AppCmp],
    引导:[AppCmp],
    导入:[浏览器模块,路由],
    提供程序:[{提供:LocationStrategy,useClass:HashLocationStrategy}]
    ]);
    
    使用
    useHash

    imports:[RouterModule.forRoot(路由器配置,{useHash:true})。。。
    
    确保您拥有所有必需的导入

    对于新的(RC.3)路由器

    
    
    也可能导致404

    相反,它需要

    
    

    更新>=RC.x

    bootstrap(AppCmp[
    路由器供应商,
    提供(LocationStrategy,{useClass:HashLocationStrategy})
    //还是从RC.2开始
    {提供:LocationStrategy,useClass:HashLocationStrategy}
    ]);
    从'@angular/core'导入{provide};
    导入{
    平台位置,
    位置,
    区位战略,
    HashLocationStrategy,
    路径定位策略,
    APP_BASE_HREF}
    从“@angular/common”开始;
    
    更新>=beta.16导入已更改

    从'@angular/platformbrowser'导入{BrowserPlatformLocation};
    从'angular2/core'导入{provide};
    进口{
    //平台位置,
    //位置,
    区位战略,
    HashLocationStrategy,
    //路径定位策略,
    APP_BASE_HREF}
    来自“angular2/路由器”;
    从'angular2/src/router/location/browser_platform_location'导入{BrowserPlatformLocation};
    

    从'angular2/core'导入{provide};
    进口{
    HashLocationStrategy
    区位战略,
    路由器供应商,
    }来自“angular2/路由器”;
    

    另请参见中断更改

    如果您使用默认的HTML位置策略,则这是所有路由器版本中的常见情况

    浏览器栏上的URL是正常的完整HTML URL,例如:
    http://localhost/route

    因此,当我们在浏览器栏中点击Enter键时,会向服务器发送一个实际的HTTP请求,以获取一个名为
    route
    的文件

    服务器没有这样的文件,而且服务器上也没有配置express之类的东西来处理请求并提供响应,因此服务器返回404 not Found,因为它找不到
    路由
    文件

    我们希望服务器返回包含单页应用程序的
    index.html
    文件。然后路由器应该启动并处理
    /route
    url,并显示映射到它的组件

    因此,为了解决这个问题,我们需要将服务器配置为在无法处理请求的情况下返回
    index.html
    (假设这是单页应用程序文件的名称),而不是404找不到

    实现这一点的方法将取决于所使用的服务器端技术
    <base href="/">
    
    <script>document.write('<base href="' + document.location + '" />');</script>
    
    @RouteConfig([
      { path: '/**', redirectTo: ['MycmpnameCmp'] }, 
       ...
      }
    ])
    
    function sendSpaFileIfUnmatched(req,res) {
        res.sendFile("index.html", { root: '.' });
    }
    
    app.use(sendSpaFileIfUnmatched);
    
    Import-WebAdministration
    # Grab the 404 handler and update it to redirect to index.html.
    $redirect = Get-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS 
    $redirect.path = "/index.html"
    $redirect.responseMode = 1
    # shove the updated config back into IIS
    Set-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS -value $redirect
    
    // in webpack
    devServer: {
        historyApiFallback: true,
        stats: 'minimal'
    }
    
    <configuration>
        <location path="." inheritInChildApplications="false">
        <system.webServer>
            <defaultDocument enabled="true">
                <files>
                    <add value="index.html" />
                </files>
            </defaultDocument>
        </system.webServer>
      </location>
    </configuration>
    
    <!doctype html>
    <html>
        <head>
            <script type="text/javascript">
                window.location.href = "http://" + document.location.host;
            </script>
        </head>
    </html>
    
    RouterModule.forRoot(routes, { useHash: true })
    
    RouterModule.forRoot(routes)
    
    http://server:port/#/path
    
    RewriteEngine On  
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    RewriteRule ^ /index.html
    
    ErrorDocument 404 /index.html
    
    <VirtualHost *:80>
      ServerName fenz.niwa.local
      DirectoryIndex index.html
      ErrorDocument 404 /index.html
    
      DocumentRoot "/Users/zhoum/Documents/workspace/fire/fire_service/dist"
      ErrorLog /Users/zhoum/Documents/workspace/fire/fire_service/logs/fenz.error.log
      CustomLog /Users/zhoum/Documents/workspace/fire/fire_service/logs/fenz.access.log combined
    
      <Directory "/Users/zhoum/Documents/workspace/fire/fire_service/dist">
        AllowOverride All
        Options Indexes FollowSymLinks
        #Order allow,deny
        #Allow from All
        Require all granted
      </Directory>
    
      Header set Access-Control-Allow-Origin "*"
      Header set Access-Control-Allow-Methods "GET, POST"
      Header set Access-Control-Allow-Credentials "true"
      Header set Access-Control-Allow-Headers "Accept-Encoding"
    </VirtualHost>
    
     app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" });
            });
    
    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    
    ...
    export class MainComponent implements OnInit {
        constructor(private router: Router) {
            let path: string = window.location.hash;
            if (path && path.length > 0) {
                this.router.navigate([path.substr(2)]);
            }
        }
    
        public ngOnInit() { }
    }
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.engine('html', require('ejs').renderFile);
    app.use(function (req, res, next) {
        return res.render('index.html');
    });
    
    "apps": [
        {
          "root": "src",
          "outDir": "views",
    
    app.get('*', function (req, res, next) {
        res.sendFile('dist/index.html', { root: __dirname });
     });
    
    <?php
    $angular='/dist/';
    if( substr($_SERVER['REQUEST_URI'], 0, strlen($angular)) == $angular ){
        $index = $_SERVER['DOCUMENT_ROOT'] . $angular . "index.html";
        http_response_code(200);
        include $index;
        die;
    }
    
    // NOT ANGULAR...
    echo "<h1>Not found.</h1>"
    
    <script>
      sessionStorage.redirect = location.href;
    </script>
    <meta http-equiv="refresh" content="0;URL='/REPO_NAME_HERE'"></meta>
    
    <script>
      (function(){
        var redirect = sessionStorage.redirect;
        delete sessionStorage.redirect;
        if (redirect && redirect != location.href) {
          history.replaceState(null, null, redirect);
        }
      })();
    </script>
    
    <configuration>
    <system.webServer>
    <rewrite>
        <rules>
        <rule name="Angular Routes" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
        </rule>
        </rules>
    </rewrite>
    </system.webServer>
    </configuration>
    
    "assets": [
        "assets",
        "favicon.ico",
        "Web.config"
      ],
    
    ng build --prod
    
    @Controller         ////don't use RestController or it will just send back the string "index.html"
    public class Redirect {
    
        private static final Logger logger = LoggerFactory.getLogger(Redirect.class);
    
        @RequestMapping(value = {"comma", "sep", "list", "of", "routes"})
        public String redirectToIndex(HttpServletRequest request) {
            logger.warn("Redirect api called for URL {}. Sending index.html back instead. This will happen on a page refresh or reload when the page is on an Angular route", request.getRequestURL());
            return "/index.html";
        }
    }
    
    @NgModule(
    {
      imports:[RouterModule.forRoot(appRoutes,{useHash:true})]
    })
    
    import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
    
    <IfModule mod_rewrite.c>
        RewriteEngine on
    
        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]
    
        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </IfModule>
    
    <error-page>
         <error-code>404</error-code>
         <location>/index.html</location>
    </error-page>
    
    <? xml version='1.0' encoding='utf-8'?>
    <Context>
      <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
    </Context>
    
      RewriteCond %{SERVLET_PATH} !-f
      RewriteRule ^/(.*)$ /index.html [L]
    
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
        RewriteRule ^ - [L]
        RewriteRule ^ ./index.html
    </IfModule>
    
    <IfModule mime_module>
          AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
        </IfModule>
        # php -- END cPanel-generated handler, do not edit
    
        <IfModule mod_rewrite.c>
            RewriteEngine on
    
            # Don't rewrite files or directories
            RewriteCond %{REQUEST_FILENAME} -f [OR]
            RewriteCond %{REQUEST_FILENAME} -d
            RewriteRule ^ - [L]
    
            # Rewrite everything else to index.html
            # to allow html5 state links
            RewriteRule ^ index.html [L]
        </IfModule>