Angular框架专题

Angular中的动态路由js跳转以及路由get传值js跳转

2021-11-02  本文已影响0人  听书先生
1、动态路由js跳转

与前面的动态路由参数大致相同,也是跳转页面的过程中,将数据传过去
在news页面中,首先引入Router模块import { Router } from '@angular/router';,导入后在construct中定义下,再进行方法的封装以及初始化操作

模板的代码:

<nz-table #basicTable [nzData]="listOfData">
    <thead>
      <tr>
        <th>编号</th>
        <th>新闻来源</th>
        <th>最近新闻</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let data of basicTable.data">
        <td>{{ data.key }}</td>
        <td>{{ data.unit }}</td>
        <td>{{ data.recent }}</td>
        <td>
          <button nz-button nzType="primary" (click)="goDetail(data)">点击跳转详情页</button>
        </td>
      </tr>
    </tbody>
  </nz-table>

  

ts部分的代码:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

interface Person {
  key: string;
  unit: string;
  recent: string;
}

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {

  listOfData: Person[] = [
    {
      key: '1',
      unit: '红星新闻',
      recent:'北京为限制进京-误伤-道歉-提醒防控还要更人性化'
    },
    {
      key: '2',
      unit: '能源需求激增-石油巨头却选择把现金返还给投资者-什么操作',
      recent: '英为财情'
    },
    {
      key: '3',
      unit: '梅新育-鼓励家庭储备生活必需品-为正常保障民生-与其他局势无关-不必过度解读',
      recent: '红星新闻'
    }
  ];

  constructor(private router: Router) { }



  ngOnInit(): void {
  }

  goDetail(query:any) {
    this.router.navigate(['/detail/',query.key])
  }

}

image.png
可以看到,在详情页中this.route.params也是同样的接收到了传过来的数据。
2、路由get传值js跳转

现在页面中引入NavigationExtras模块

import { Component, OnInit } from '@angular/core';
import { Router,NavigationExtras } from '@angular/router';

interface Person {
  key: string;
  unit: string;
  recent: string;
}

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {

  listOfData: Person[] = [
    {
      key: '1',
      unit: '红星新闻',
      recent:'北京为限制进京-误伤-道歉-提醒防控还要更人性化'
    },
    {
      key: '2',
      unit: '能源需求激增-石油巨头却选择把现金返还给投资者-什么操作',
      recent: '英为财情'
    },
    {
      key: '3',
      unit: '梅新育-鼓励家庭储备生活必需品-为正常保障民生-与其他局势无关-不必过度解读',
      recent: '红星新闻'
    }
  ];

  constructor(private router: Router) { }



  ngOnInit(): void {
  }

  goDetail(query:any) {
    this.router.navigate(['/detail/',query.key])
  }

  goNewDetail(query:any) {
    let navigationExtras: NavigationExtras = {
      queryParams:{name:'zhangsan'},
      fragment:'anchor'
    }

    this.router.navigate(['/detail/',query.key],navigationExtras)
  }

}

通过封装一个goNewDetail方法去执行跳转,用 NavigationExtras 配置传参
不同的是,这里接收时不再是params接收,而是queryParams去接收

  ngOnInit(): void {
    
    console.log(this.route.queryParams); 
    this.route.params.subscribe(data => this.id=data.id);
  }
image.png

可以看到,使用NavigationExtras 传值仍然能够接收到传过来的值。

上一篇 下一篇

猜你喜欢

热点阅读