【问题标题】:Route changes dynamically路由动态变化
【发布时间】:2018-09-08 16:07:07
【问题描述】:

我正在使用jwt token 来检查用户是否在orderscomponent.ts 中登录,如下所示

let userkey = this.storage.get("token");
if (!userkey) {
    this.router.navigate(['signup']);
} 

然后导航到基于if-conditionsignup 页面。重定向sign up 页面后,我正在填写表格。点击sign up按钮代码如下signupcomponent.ts

<button type="submit" (click)="onSignUp()" class="btn btn-info btn-lg btn-block btn-rounded text-uppercase waves-effect waves-light"></button>

componet.ts 我有如下代码

onSignUp(){
    this.router.navigate([`orderpage`])
}

登录用户后,它会重定向到orderpage 的同一页面,直到这里它工作正常。

现在我的问题是我正在使用相同的signupcomponent.ts 在主页中。当我点击注册时,它会将我带到注册页面,当我点击注册按钮时,它应该重定向到相同的主页或个人资料页面。这里我的意思是我想改变this.router.navigate([]) params once already definedurlto another newurl`

【问题讨论】:

  • 你能把你的代码发到stackblitz.com
  • 你明白我的问题了吗??
  • 我不明白这个问题。
  • 你不明白什么?请告诉我,我会解释得更清楚
  • 您想根据父组件导航到另一个 url 吗?

标签: angular typescript


【解决方案1】:

正如@James Glasgow 所说,您可以使用服务来实现您的目标。

它看起来像以下示例:

Service

@Injectable()
export class RouterHelper {
    redirectUrl: string = 'orderpage'; // Defined orderpage as default
}

orderscomponent.ts

this.router.navigate(['signup']).then((successful: boolean) => {
    // Only set the redirectUrl, if the routing is successful
    if (successful) {
        this.routerHelper.redirectUrl = 'orderspage';
    }
});

homepage.component.ts

this.router.navigate(['signup']).then((successful: boolean) => {
    // Only set the redirectUrl, if the routing is successful
    if (successful) { 
        this.routerHelper.redirectUrl = 'homepage'; 
    }
});

另一种方法是使用 urls 参数:

为此,您可以在两个组件的导航功能中添加参数,如下所示:

this.router.navigate(['signup', { parentUrl: 'orderpage'}]);

在你的signupcomponent.ts:

onSignUp() {
    const parentUrl = this.route.snapshot.paramMap.get('parentUrl');
    this.router.navigate([parentUrl]);
}

如果您要重复使用您的signupcomponent.ts,您应该订阅路由器参数(请参阅here)。

【讨论】:

    【解决方案2】:

    有两种主要的使用方式

    将返回 url 传递给服务并由其使用

    this.router.navigate([[this.urlService.redirectUrl]]);
    

    您只需将 url 存储在服务中

    其他使用方式

    this.location.back();
    

    弹出堆栈并返回上一页Location Docs

    【讨论】:

    • 我没有得到答复。你能分享一个活生生的例子吗
    猜你喜欢
    • 2017-11-25
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2015-01-05
    • 2015-02-20
    • 2021-12-01
    相关资源
    最近更新 更多