如何在Angular 2中重定向页面

时间:2018-07-18 05:42:53

标签: angular routes angular-ui-router angular2-routing router

当前页面为http://localhost:4200/#/workrec-list

我想去http://localhost:4200/#/single

如何做到有角度呢?

我有

this.router.navigate(['/single'], {queryParams: {month: this.data.month}});

但是它不起作用。并且有错误

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '/single'

2 个答案:

答案 0 :(得分:1)

    This code will help you to solve redirection problem of yours i am also attaching jsfiddle[link text](http://jsfiddle.net/5DMjt/25081/)


            <html ng-app="myApp">
            <head>
            </head>
            <body ng-controller="myCtrl">
                <p> <a href="https://docs.woocommerce.com/document/create-a-plugin/"><button>Click me to redirect from template</button></a></p>
                <p ng-click="myFunction()"> <button>Click me to redirect from controller</button></p>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
            <script>
                var app = angular.module('myApp',[]);
                app.controller('myCtrl',function($window,$scope){
                    $scope.myFunction = function(){
                    $window.location.href = 'http://delmarts.com/'; //You should have http here.
                    }
                });
            </script>
            </body>
            </html>

答案 1 :(得分:0)

我们可以使用 RoutingModule 来做到这一点,在此示例中,我们将使用2个组件: Component1 Component2 创建一个名为< strong> app.routing.ts :

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Component1 } from './component1.component';
import { Component2 } from './component2.component';
const appRoutes: Routes = 
       [{ path: 'component1', component: Component1 },
        { path: 'component2', component: Component2 }];
 export const appRoutingProviders: any[] = [];
 export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

我已经定义了路径 / component1 / component2 ,这将允许我重定向到两个组件。

接下来,我们必须按如下所示在app.module.ts上导入路由配置:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { routing, appRoutingProviders }  from './app.routing';
import { Component1 } from './component1.component';
import { Component2 } from './component2.component';

@NgModule({
imports:      [ BrowserModule, routing ],
declarations: [ AppComponent, Component1, Component2],
providers:    [appRoutingProviders],
bootstrap:    [ AppComponent ]
})
export class AppModule { }

现在您可以通过将路径传递到常规链接的 routerLink 属性来进行重定向:

<a routerLink="/component1" >Component 1</a>
<a routerLink="/component2" >Component 2</a>

我已经尝试过这个示例,希望对您有所帮助。...