【问题标题】:Send data through routing paths in Angular通过 Angular 中的路由路径发送数据
【发布时间】:2017-12-05 11:12:33
【问题描述】:

到底有没有用 router.navigate 发送数据作为参数? 我的意思是,类似this 的例子,你可以看到路由有一个数据参数,但是这样做是行不通的:

this.router.navigate(["heroes"], {some-data: "othrData"})

因为 some-data 不是有效参数。我怎样才能做到这一点?我不想用 queryParams 发送参数。

【问题讨论】:

标签: angular routing angular-router


【解决方案1】:

关于这个话题有很多困惑,因为有很多不同的方法可以做到这一点。

以下是以下屏幕截图中使用的适当类型:

private route: ActivatedRoute
private router: Router

1) 所需的路由参数:

2) 路由可选参数:

3) 路由查询参数:

4) 您可以使用服务将数据从一个组件传递到另一个组件,而无需使用路由参数。

示例见:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

我在这里有一个小插曲:https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

【讨论】:

  • 感谢您的回答! 2)和3)有什么区别?因为两者最终都在 URL 中添加了“?parameter=”。你能给我举个4)的例子吗?我不知道该怎么做。
  • 我更新了答案以显示不同的 URL,并提供指向博客文章的链接以及如何通过服务传递数据的 plunker。 URL 与可选参数和查询参数不同,如上所示。 Plus 查询参数可以跨路由保留。
  • 我还有一个关于路由的 Pluralsight 课程,涵盖了所有这些:app.pluralsight.com/library/courses/angular-routing/… 如果您有兴趣了解更多信息,可以免费注册一周。
  • 数据仅在执行应用程序中“共享”。如果用户刷新页面,则从服务器重新加载整个应用程序,因此应用程序中不会保留先前的状态。从普通应用程序的角度考虑,当用户刷新时,它就像关闭和重新打开应用程序一样。如果您需要在刷新后保留状态,则需要将其存储在某个地方,例如本地存储或服务器上。
  • 只是一个小提示:route 类型是 ActivatedRoute,而不是 Router
【解决方案2】:

Angular 7.2.0 附带了一种新方法

https://angular.io/api/router/NavigationExtras#state

发送:

    this.router.navigate(['action-selection'], { state: { example: 'bar' } });

接收:

    constructor(private router: Router) {
      console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
    }

您可以在此处找到一些其他信息:

https://github.com/angular/angular/pull/27198

上面的链接包含这个很有用的例子: https://stackblitz.com/edit/angular-bupuzn

【讨论】:

  • 鉴于 Angular 7 中的新功能,这是正确答案。
  • 使用这种方法,我将如何处理用户刷新浏览器?在这种情况下,附加导航中的数据似乎消失了,因此在刷新时没有机会再次使用它。
  • 是的,这就是为什么您只能从构造函数中的 this.router.getCurrentNavigation() 获取数据的原因。如果您在其他地方需要它,例如在 ngOnInit() 内部,您可以通过“history.state”访问数据。从文档中:“状态传递给任何导航。在执行导航时,可以通过从 router.getCurrentNavigation() 返回的附加对象访问此值。导航完成后,该值将在定位时写入 history.state .go 或 location.replaceState 方法在激活此路由之前被调用。"
  • 另外,请确保您不要尝试在 ngOnInit() 中以 this.router.getCurrentNavigation().extras 接收 extras 对象
  • @KinleyChristian 查看此答案,如果您还有其他问题,请告诉我! stackoverflow.com/a/54891361/4222504
【解决方案3】:

最新版本的 angular (7.2 +) 现在可以选择使用 NavigationExtras 传递附加信息。

首页组件

import {
  Router,
  NavigationExtras
} from '@angular/router';
const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};
this.router.navigate(['newComponent'], navigationExtras);

新组件

test: string;
constructor(private router: Router) {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state as {
    transId: string,
    workQueue: boolean,
    services: number,
    code: string
  };
  this.test = "Transaction Key:" + state.transId + "<br /> Configured:" + state.workQueue + "<br /> Services:" + state.services + "<br /> Code: " + state.code;
}

输出

希望这会有所帮助!

【讨论】:

  • 我不断收到“导航为空”。我已经尝试了几个例子......
  • 这是旧的,但对于未来的访问者 - 你必须在构造函数中调用它。 stackoverflow.com/a/54891361/2950032
  • 页面刷新后还能访问状态数据吗?
  • 好的,我刚刚自己测试过,只有在从旧组件路由到新组件后才能完美运行。重新加载页面后,状态未定义:(
  • 这在用户重新加载页面之前完美运行。那么状态将是未定义的。 :(
【解决方案4】:

@dev-nish 您的代码只需稍加调整即可工作。 制作

const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};

进入

let navigationExtras: NavigationExtras = {
  state: {
    transd: '',
    workQueue: ,
    services: ,
    code: ''
  }
};

如果您想专门发送一种类型的数据,例如作为表单填写结果的 JSON,您可以按照前面解释的方式发送数据。

【解决方案5】:

在 navigateExtra 中,我们只能传递一些特定的名称作为参数,否则会显示如下错误: 对于Ex-在这里我想在路由器导航中传递客户密钥,我像这样传递-

this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});

但它显示如下错误:

Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
  Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'

.

解决方案: 我们必须这样写:

this.Router.navigate(['componentname'],{state: {customerkey:response.key}});

【讨论】:

    【解决方案6】:

    我在互联网上找到的最好的是ngx-navigation-with-data。 它非常简单,非常适合将数据从一个组件导航到另一个组件。 您只需导入组件类并以非常简单的方式使用它。 假设你有 home 和 about 组件,然后想发送数据

    家庭组件

    import { Component, OnInit } from '@angular/core';
    import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';
    
    @Component({
     selector: 'app-home',
     templateUrl: './home.component.html',
     styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
    
    constructor(public navCtrl: NgxNavigationWithDataComponent) { }
    
     ngOnInit() {
     }
    
     navigateToABout() {
      this.navCtrl.navigate('about', {name:"virendta"});
     }
    
    }
    

    关于组件

    import { Component, OnInit } from '@angular/core';
    import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';
    
    @Component({
     selector: 'app-about',
     templateUrl: './about.component.html',
     styleUrls: ['./about.component.css']
    })
    export class AboutComponent implements OnInit {
    
     constructor(public navCtrl: NgxNavigationWithDataComponent) {
      console.log(this.navCtrl.get('name')); // it will console Virendra
      console.log(this.navCtrl.data); // it will console whole data object here
     }
    
     ngOnInit() {
     }
    
    }
    

    如有任何疑问,请关注https://www.npmjs.com/package/ngx-navigation-with-data

    留言寻求帮助。

    【讨论】:

    • 是以参数的形式传输数据还是仅在后台传输数据?
    • 我听不懂@MariumMalik 你能用描述性的方式提问吗?
    • 是的,@MariumMalik
    • 您似乎是本文的作者,而不是“我在互联网上找到的”?您还被要求不要在实现类似功能的 Angular 7 线程上发送垃圾邮件 (github.com/angular/angular/pull/27198)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2019-10-28
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多